An implementation of the Resource pattern in Ember.JS.
npm install ember-resources
# or
yarn add ember-resources
# or
ember install ember-resources
See: API Documentation for more examples.
import { trackedFunction } from 'ember-resources/util/function';
class MyClass {
@tracked endpoint = 'starships';
data = trackedFunction(this, async () => {
let response = await fetch(`https://swapi.dev/api/${this.endpoint}`);
let json = await response.json();
return json.results;
}),
get records() {
return this.data.value ?? [];
}
}
{{this.records}}
In this example, trackedFunction will make a call to StarWars API
and if endpoint changes from starships to planets, the trackedFunction will
automatically re-call the StarWars API to fetch the planets.
Visit the docs on function-based resources.
This alternate API is more general-purpose, but has the same behavior as the above example.
import { resource, use } from 'ember-resources';
import { TrackedObject } from 'tracked-built-ins';
class MyClass {
@tracked endpoint = 'starships';
@use load = resource(({ on }) => {
let state = new TrackedObject({});
let controller = new AbortController();
on.cleanup(() => controller.abort());
fetch(`https://swapi.dev/api/${this.endpoint}`, { signal: controller.signal })
.then(response => response.json())
.then(data => {
state.value = data;
// ...
})
.catch(error => {
state.error = error;
// ...
});
return state;
});
}
{{#if this.load.value}}
...
{{else if this.load.error}}
{{this.load.error}}
{{/if}}
Resources [...] bridge a gap between imperative programming and declarative programming.
Ember templates are declarative. When we design a component [...] we are specifying declaratively the HTML that should be rendered. If the data used in the templates ever updates, then Ember will update the rendered output as well, and we don't have to worry about the details. We don't have to tell Ember which specific steps to take, and when - it figures everything out for us.
Generated using TypeDoc