Skip to content

Instantly share code, notes, and snippets.

@sukima
Last active May 9, 2024 23:55
Show Gist options
  • Save sukima/c85fe597f6984de36e8adf9b4d2c9c04 to your computer and use it in GitHub Desktop.
Save sukima/c85fe597f6984de36e8adf9b4d2c9c04 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const parseScannedData =
(context, event) => {
return (callback) => {
// This should be something that gets the json:
let { json } = {} // doSomethingAsync();
let isValid = Array.isArray(json);
if (!isValid) {
callback({ type: 'SCAN_ERROR' });
} else {
callback({ type: 'SCAN_DONE', data: json });
}
};
};
const foo = Machine({
id: 'scan-qr-code',
strict: true,
initial: 'idle',
context: {
intent: undefined,
data: undefined,
},
states: {
idle: {
on: {
SCAN: 'scanned'
}
},
// Maybe you mean scanning as the scan is async and is kicked off by the invoked parse service?
scanned: {
invoke: {
// I like to name my src and define it in the services section so thatthe machine itself remains implementation agnostic. But this is ok for prototyping like you are now.
id: 'parse',
src: parseScannedData,
// Have sync errors do something. (invoking callbacks)
// Or when an async error happens (invoking promises)
onError: 'scanError'
},
on: {
SCAN_DONE: {
target: 'loginRequest',
actions: assign({
intent: (_, event) => event.data[0],
data: (_, event) => event.data[1],
})
},
// Because we used a callback for the service we control the events it sends hence the custom error event used here.
SCAN_ERROR: 'scanError'
}
},
scanError: {
entry: () => console.log('entered scanError'),
},
loginRequest: {
entry: () => console.log('entered login request'),
},
addFriend: {},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment