Skip to content

Instantly share code, notes, and snippets.

@mrsln
Created July 21, 2020 11:30
Show Gist options
  • Save mrsln/56a47ccbce437fdd08a42c9caade24f0 to your computer and use it in GitHub Desktop.
Save mrsln/56a47ccbce437fdd08a42c9caade24f0 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const fetchMachine = Machine(
{
initial: "loading",
id: "fetch",
context: {
url: "https://www.random.org/integers/?num=1&min=1000&max=10000&col=5&base=10&format=plain&rnd=new",
},
states: {
loading: {
invoke: {
src: (context, _) => {
return fetch(context.url, { cache: "no-cache" })
.then((response) =>
Promise.all([Promise.resolve(response), response.json()])
)
.then(([response, body]) => ({ response, body }));
},
onDone: [
{
target: "successFinal",
cond: (_, event) => event.data && event.data.response.ok,
actions: assign((_, event) => {
return { body: event.data && event.data.body };
}),
},
{
target: "failureFinal",
actions: assign({
error: (_) => "Status code was not between 200-299",
}),
},
],
onError: {
target: "failureFinal",
actions: assign({ error: (_) => "Network error has occurred" }),
},
},
after: {
TIMEOUT_DELAY: {
target: "failureFinal",
actions: assign({
error: (context) =>
`Timeout has occur after waiting for 7000 milliseconds`,
}),
},
},
},
successFinal: {
type: "final",
data: (context, _) => ({ body: context.body }),
},
failureFinal: {
type: "final",
data: (context, _) => ({ error: context.error }),
},
},
},
{
delays: {
TIMEOUT_DELAY: 7000,
},
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment