Last active
December 13, 2018 01:34
-
-
Save hnordt/13e0dda6b43a46643a89978229e2d647 to your computer and use it in GitHub Desktop.
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
// 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