Skip to content

Instantly share code, notes, and snippets.

@hnordt
Last active December 13, 2018 01:34
Show Gist options
  • Save hnordt/13e0dda6b43a46643a89978229e2d647 to your computer and use it in GitHub Desktop.
Save hnordt/13e0dda6b43a46643a89978229e2d647 to your computer and use it in GitHub Desktop.
// Previewable on https://statecharts.github.io/xstate-viz/
const { assign } = XState.actions
const MAX_RETRY_COUNT = 3
const fetchMachine = Machine(
{
id: "fetch",
initial: "idle",
context: {
url: "https://api.ipify.org?format=json",
data: null,
error: null,
retries: 0
},
states: {
idle: { on: { FETCH: "loading" } },
loading: {
invoke: {
src: "fetch",
onDone: {
target: "success",
actions: "setData"
},
onError: {
target: "failure",
actions: "setError"
}
}
},
success: {
on: {
REFETCH: {
target: "loading",
actions: "resetRetries"
}
}
},
failure: {
on: {
"": {
target: "fatal",
cond: "canNotRetry"
},
RETRY: {
target: "loading",
actions: "incrementRetries"
}
}
},
fatal: {
type: "final"
}
}
},
{
guards: {
canNotRetry: ({ retries }) => retries === MAX_RETRY_COUNT
},
actions: {
setData: assign({ data: (_, { data }) => data }),
setError: assign({ error: (_, { data }) => data }),
incrementRetries: assign({ retries: ({ retries }) => retries + 1 }),
resetRetries: assign({ retries: 0 })
},
services: {
fetch: ({ url }) => fetch(url).then(res => res.json())
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment