Skip to content

Instantly share code, notes, and snippets.

@sukima
Last active June 18, 2020 00:46
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 sukima/3595b05fc2c61593950b5a4681bef124 to your computer and use it in GitHub Desktop.
Save sukima/3595b05fc2c61593950b5a4681bef124 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)
function mockFetch() {
return new Promise(resolve => {
setTimeout(
() => resolve('ok'),
2000
);
});
}
function mockError() {
return new Promise((_, reject) => {
setTimeout(
() => reject(new Error('bork')),
2000
);
});
}
const fetchMachine = Machine({
id: 'complex-fetch',
initial: 'idle',
context: { errors: [] },
states: {
idle: {
on: { START: 'fetching' }
},
fetching: {
type: 'parallel',
on: { STOP: 'idle' },
states: {
batch1: {
initial: 'pending',
states: {
pending: {
invoke: {
src: 'fetchBatch1',
onDone: {
target: 'done',
actions: 'storeDataBatch1'
},
onError: {
target: 'error',
actions: 'storeError'
}
}
},
done: { type: 'final' },
error: { type: 'final' }
}
},
batch2: {
initial: 'pending',
states: {
pending: {
invoke: {
src: 'fetchBatch2',
onDone: {
target: 'done',
actions: 'storeDataBatch2'
},
onError: {
target: 'error',
actions: 'storeError'
}
}
},
done: { type: 'final' },
error: { type: 'final' }
}
}
}
}
}
}, {
actions: {
storeDataBatch1: assign({
batch1: (_, { data }) => data
}),
storeDataBatch2: assign({
batch2: (_, { data }) => data
}),
storeError: assign({
errors: ({ errors }, { data }) => {
return [ ...errors, data ];
}
})
},
services: {
fetchBatch1: mockFetch,
fetchBatch2: mockError
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment