Invoking Services: Async Operations
You'll learn how to model promises, callbacks, and observables as invoked services that send events back to XState machines.
The Core Idea
In XState, invoked services let you kick off asynchronous operations (like API calls or timers) when a machine enters a certain state. Unlike actions that fire-and-forget, invoked services are ongoing processes that can send events back to the machine as they progress, succeed, or fail. Think of them as delegates you dispatch—they report back with updates, and your machine reacts accordingly.
How It Works
When a state has an invoke property, XState starts the service upon entering that state. The service can be a promise, callback function, or observable. As the service runs, it sends events like { type: 'done.invoke.serviceName', data: result } on success or { type: 'error.platform.serviceName', data: error } on failure.
const fetchMachine = createMachine({
initial: 'loading',
states: {
loading: {
invoke: {
id: 'fetchUser',
src: () => fetch('/api/user').then(res => res.json()),
onDone: {
target: 'success',
actions: (context, event) => console.log(event.data)
},
onError: 'failure'
}
},
success: { type: 'final' },
failure: { type: 'final' }
}
});
Here, entering loading invokes the fetch promise. When it resolves, the machine automatically transitions to success. If it rejects, it goes to failure.
Why This Matters
Invoked services formalize async workflows: no scattered useEffect cleanup, no manual loading flags—just declarative state transitions. Your machine knows exactly when async work is happening and what to do with the results.
Key Takeaway: Invoked services model asynchronous operations as first-class citizens in state machines, sending completion or error events that drive state transitions cleanly and predictably.