Skip to content

Instantly share code, notes, and snippets.

@callumlocke
Last active March 9, 2020 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callumlocke/d71d6492149de1f71d53efde3e80d940 to your computer and use it in GitHub Desktop.
Save callumlocke/d71d6492149de1f71d53efde3e80d940 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const loadJsonString = assign({
jsonString: (context, event) => {
// HACK
return '{"foo":[123]}'
if (typeof event.json !== 'string') {
throw new TypeError('Expected LOAD_JSON event to include a string')
}
return event.json
}
});
const attemptParse = assign((context, event) => {
let parsedJson = null;
let jsonError = null;
try {
parsedJson = JSON.parse(context.jsonString);
} catch (error) {
jsonError = error;
}
return {
parsedJson,
jsonError,
};
});
const machine = Machine({
id: 'jf',
initial: 'idle',
strict: true,
context: {
jsonString: null,
parsedJson: null,
jsonError: null,
activeUpdateJob: null, // one at a time
},
states: {
idle: {
on: {
LOAD_JSON_STRING: {
actions: loadJsonString,
target: 'loading',
},
},
},
loading: {
entry: [
attemptParse,
send('LOADED'),
],
on: {
LOADED: [
{
target: 'loadedInvalidJson',
cond: context => context.jsonError !== null,
},
{
target: 'loadedValidJson',
cond: (context) => context.jsonError === null,
}
]
},
},
loadedInvalidJson: {
on: {
LOAD_JSON_STRING: {
actions: loadJsonString,
target: 'loading',
},
},
},
loadedValidJson: {
},
},
actions: {
attemptParse,
},
guards: {},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment