Skip to content

Instantly share code, notes, and snippets.

@bfunc
Created April 11, 2021 22:56
Show Gist options
  • Save bfunc/6c3f3581ce452f2007443b76e6d03feb to your computer and use it in GitHub Desktop.
Save bfunc/6c3f3581ce452f2007443b76e6d03feb to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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