#services in xstate 5

1 messages · Page 1 of 1 (latest)

drowsy nymph
#

What is the equivalent to services in xstate 5?

I have tried fromPromise, that works but I do not always want to return a promise.

I intend to define an async function that does a firebase read and then an axios call (so a chain of promises), and then onDone or onErrors when that whole function finishes. Is there a way to do this in a single code block or do I have to compose individual state transitions something like that?

pseudocode ish example of what I would like to do in xstate 5:

const myMachine = createMachine({
//some machine...
},
{
  services:{
    getUser: async (event, context)=>{
      const user = await context.db.collection("users").get();
      //do some logic about that user
      const userData = await context.db.somethingElseBasedOnThatLogic();
      const data = //manipulate userData;
      const response = axios.post(url,data);
    }
  }
}
)

Thank you

cobalt canyon
# drowsy nymph What is the equivalent to services in xstate 5? I have tried fromPromise, that ...

I think you want something like this:

someState: {
  invoke: {
    src: "getUser",
    input: ({ context, event }) => {
      // ...
    },
  }
}

actors: {
  getUser: fromPromise(async ({ input }) => {
    const user = await input.context.db.collection("users").get();
    //do some logic about that user
    const userData = await input.context.db.somethingElseBasedOnThatLogic();
    // const data = manipulate userData;
    const response = axios.post(url, data);
  });
}```
#

...then you can use onDone() to get the final output of the actor.

#

...or this?

actor.subscribe(snapshot => {
  if (snapshot.status === 'done') {
    console.log(snapshot.output.message);
  }
});
scarlet yarrow
drowsy nymph
#

Thanks both