Last active
June 18, 2020 00:46
-
-
Save sukima/3595b05fc2c61593950b5a4681bef124 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains hidden or 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) | |
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