XState: Using invoke and always when loading data inside a state machine

When using the invoke property to load external data you'll likely make use of the onDone and onError properties:

invoke: { src: 'getDataService', onDone: 'success', onError: 'failure', },

If you want to immediately do something with that successfully loaded data you can use the always property inside the success state with some conditions:

success: { always: [ // <--- The good bit { target: 'incomingSession', cond: 'isIncomingSession', }, { target: 'sessionActive', cond: 'isSessionActive', }, ... ] }

This is saying: When entering the success state, always go to one of the target states based on the given condition (cond). For example; if the current session is active (isSessionActive), go to the sessionActive state.

This is something that took a little while to click for me when learning XState, so hopefully this is helpful!

This state machine was used as part of the Saving Sessions campaign at Octopus Energy 👇

Saving sessions website

The dashboard for this project has a total of 11 states it could possibly be in, so a state machine felt right for this one.