Created
January 4, 2020 15:39
-
-
Save medelman17/53c85d9a62164a72c4d9ed818fecc4b7 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
This file contains hidden or 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
const options = { | |
guards: { | |
shouldRetry: (context, event) => { | |
return context.retries < 4; | |
} | |
}, | |
actions: { | |
incrementRetries: assign({ | |
retries: (context, event) => context.retries + 1 | |
}), | |
returnResult: assign({ | |
result: (context, event) => event.data | |
}), | |
returnError: assign({ | |
errors: (context, event) => [...context.errors, event] | |
}) | |
}, | |
activities: {}, | |
services: { | |
fetch: (context, event) => { | |
const { options } = context; | |
const { url, params, responseType } = options; | |
return fetch.get(url, { | |
params, | |
responseType | |
}); | |
} | |
}, | |
delays: { | |
FETCH_DELAY: (context, event) => { | |
return context.retries * 1000; | |
} | |
} | |
}; | |
const fetchMachine = Machine({ | |
id: "fetchMachine", | |
initial: "idle", | |
context: { | |
result: null, | |
errors: [], | |
retries: 0, | |
options: { | |
url: "", | |
params: {} | |
} | |
}, | |
states: { | |
idle: { | |
on: { | |
FETCH: "loading" | |
} | |
}, | |
loading: { | |
invoke: { | |
id: "handleFetch", | |
src: "fetch", | |
onError: { | |
target: "error", | |
actions: ["returnError"] | |
}, | |
onDone: { | |
target: "success", | |
actions: ["returnResult"] | |
} | |
} | |
}, | |
success: { type: "final" }, | |
error: { | |
entry: send("RETRY", { delay: "FETCH_DELAY" }), | |
on: { | |
RETRY: [ | |
{ | |
target: "loading", | |
cond: "shouldRetry", | |
actions: "incrementRetries" | |
}, | |
{ target: "failure" } | |
] | |
} | |
}, | |
failure: { type: "final" } | |
} | |
}, options); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment