resource
is an alternative API to the class-based Resource
.
It may provide a single read-only value and provides a way to optionally cleanup.
When would you reach for the class-based Resource
?
A function-resource
Example using fetch
+ AbortController
import { resource } from 'ember-resources';
import { TrackedObject } from 'tracked-built-ins';
import { tracked } from '@glimmer/tracking';
class Demo {
@tracked url = '...';
myData = resource(this, ({ on }) => {
let state = new TrackedObject({ isResolved: false, isLoading: true, isError: false });
let controller = new AbortController();
on.cleanup(() => controller.abort());
// because this.url is tracked, anytime url changes,
// this resource will re-run
fetch(this.url, { signal: controller.signal })
.then(response => response.json())
.then(data => {
state.value = data;
state.isResolved = true;
state.isLoading = false;
state.isError = false;
})
.catch(error => {
state.error = error;
state.isResolved = true;
state.isLoading = false;
state.isError = true;
});
// Note that this fetch request could be written async by wrapping in an
// immediately invoked async function, e.g: (async () => {})()
return state;
})
}
Generated using TypeDoc
resource
is an alternative API to the class-basedResource
. It may provide a single read-only value and provides a way to optionally cleanup.Arguments passed to the
resource
function:When would you reach for the class-based
Resource
?A function-resource
Example using
fetch
+AbortController
Example using strict mode +
<template>
syntax and a template-only component: