ember-resources

ember-resources

npm version CI An implementation of the Resource pattern in Ember.JS.

Compatibility

  • ember-source v3.28+
  • typescript v4.5+
  • ember-auto-import v2+
  • Glint 0.8.3+
    • Note that updates to glint support will not be covered by this library's adherance to SemVer. All glint-related updates will be bugfixes until Glint is declared stable.

Installation

npm install ember-resources
# or
yarn add ember-resources
# or
ember install ember-resources

See: API Documentation for more examples.

Example (async utility)

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.

Example (function-based resource)

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}}

What is a Resource?

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.

pzuraq on "Introducing

Generated using TypeDoc