Last active
March 9, 2020 18:23
-
-
Save callumlocke/d71d6492149de1f71d53efde3e80d940 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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