Skip to content

Instantly share code, notes, and snippets.

@mwarger
Last active March 8, 2020 19:00
Show Gist options
  • Save mwarger/5ce220ac48552173a6b2729edced7e56 to your computer and use it in GitHub Desktop.
Save mwarger/5ce220ac48552173a6b2729edced7e56 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const fetchMachine = Machine(
{
id: "fetch",
initial: "idle",
context: {
url: {},
data: null,
error: null,
retries: 0,
maxRetries: 3
},
states: {
idle: {
on: {
FETCH: "loading"
}
},
loading: {
invoke: {
src: "fetch",
onDone: {
target: "success",
actions: ["setData", "notifyData"]
},
onError: {
target: "failure",
actions: ["setError", "notifyError"]
}
}
},
success: {
on: {
REFETCH: {
target: "loading",
actions: "resetRetries"
}
}
},
failure: {
on: {
"": {
target: "fatal",
cond: "canNotRetry"
},
RETRY: {
target: "loading",
actions: "incrementRetries"
}
}
},
fatal: {
type: "final"
}
}
},
{
guards: {
canNotRetry: ({ retries, maxRetries }) => retries === maxRetries
},
actions: {
setData: assign({ data: (_, event) => event.data }),
notifyData: () => {},
setError: assign({ error: (_, event) => event.data }),
notifyError: () => {},
incrementRetries: assign({ retries: context => context.retries + 1 }),
resetRetries: assign({ retries: 0 })
},
services: {
fetch: context => axios(context.url).then(response => response.data)
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment