ember icon indicating copy to clipboard operation
ember copied to clipboard

Add recipe for using Microstates with Ember Concurrency

Open taras opened this issue 5 years ago • 0 comments

There is nothing really tricky about using Microstates with Ember Concurrency, but we do want to make this clearer with a good example. For all intents and purposes, Microstates behave like Computed Properties. You can write values to them and the result will be computed synchronously when the value is read. Microstates also debounce no-op write operations.

To use Microstates with EC, you would probably want to define the state on the component rather than in the template. It's possible to send a microstate as an argument to the task, so that could be an option for microstates defined in the template.

import Component from '@ember/microstates';
import { state } from '@microstates/ember';
import { task } from 'ember-concurrency';
import fetch from 'ember-network';

class Person {
  name = String;
  age = String;

  get summary() {
   return `${this.name.state} is ${this.age.state}`;
  }
}

export default Component.extend({
  person: state(Person),

  fetchPerson: task(function *() {

    let response = yield fetch('person');
    let person = yield response.json();

    this.get('person').set(person);

    return this.get('person.summary');
  })
});

taras avatar Nov 27 '18 14:11 taras