Created
April 11, 2021 22:56
-
-
Save bfunc/6c3f3581ce452f2007443b76e6d03feb 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
const wait = ms => new Promise(r => setTimeout(() => r(), ms)); | |
const fetchPosts = (context, event) => { | |
const { q: num } = context; | |
console.log('> fetchPosts',num) | |
if (num == 5) { | |
return new Promise((r, reject) => reject(new Error('Oh too bad...'))); | |
} | |
if (num % 2) { | |
return new Promise(resolve => resolve({ id: Math.random(), title: 'foo' })); | |
} | |
return fetch('https://jsonplaceholder.typicode.com/posts/' + num) | |
.then(res => res.json()) | |
.then(data => { | |
return data; | |
}); | |
}; | |
/* const fetchPosts = async (context, event) => { | |
const result = await fetchPostsSrc(context, event); | |
console.log({ result }); | |
await wait(1000); | |
return result; | |
}; */ | |
const fetchMachine = Machine({ | |
id: 'fetch', | |
initial: 'idle', | |
context: { | |
retries: 0, | |
q: 0, | |
error: '', | |
}, | |
states: { | |
idle: { | |
on: { | |
FETCH: 'loading', | |
}, | |
}, | |
loading: { | |
invoke: { | |
id: 'fetchPosts', | |
src: fetchPosts, | |
onDone: { | |
target: 'success', | |
actions: (c, e) => { | |
c.q += 1; | |
console.log({ success: e.data }); | |
}, | |
}, | |
onError: { | |
target: 'failure', | |
actions: (c, e) => { | |
console.log({ fail: e.data }); | |
}, | |
}, | |
}, | |
on: { | |
RESOLVE: 'success', | |
REJECT: 'failure', | |
}, | |
}, | |
success: { | |
//type: 'final', | |
on: { | |
RETRY: { | |
target: 'loading', | |
}, | |
}, | |
}, | |
failure: { | |
on: { | |
RETRY: { | |
target: 'loading', | |
actions: assign({ | |
retries: (context, event) => context.retries + 1, | |
}), | |
}, | |
}, | |
}, | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment