Skip to content

Instantly share code, notes, and snippets.

@RafalFilipek
Created April 9, 2020 10:27
Show Gist options
  • Save RafalFilipek/e1317b3d4e7cc6337b3f18f81251264b to your computer and use it in GitHub Desktop.
Save RafalFilipek/e1317b3d4e7cc6337b3f18f81251264b to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const fetchMachine = Machine(
{
id: "accounts",
initial: "init",
context: {
selectedAccount: null,
transactions: []
},
states: {
init: {
entry: "setDefaultAccountCandidate",
invoke: {
id: "fetchingAccounts",
src: "fetchAccounts",
onDone: {
target: "ready",
actions: "setAccounts"
},
onError: {
target: "error"
}
}
},
ready: {
id: "ready",
initial: "idle",
on: {
RETURN: {
target: "success",
actions: "setDefaultAccountCandidate"
},
SELECT: {
target: ".selected"
},
SET_ACCOUNT_CANDIDATE: {
target: ".idle",
actions: "setAccountCandidate"
}
},
states: {
idle: {},
fail: {},
selected: {
on: {
CONFIRM: {
target: "#processing"
}
}
},
processing: {
id: "processing",
invoke: {
id: "sendingAccount",
src: "sendAccountAndFetchTransactions",
onDone: {
target: "#success",
actions: "setTransactions"
},
onError: {
target: "fail"
}
}
}
}
},
success: {
id: "success",
type: "final",
data: context => ({
__type: "success",
hasAccountBeenChanged:
context.selectedAccount !== context.candidateAccount,
selectedAccount: context.candidateAccount || null,
transactions: context.transactions
})
},
error: {
type: "final",
data: () => ({
__type: "error",
code: "FETCHING_ACCOUNTS_ERROR"
})
}
}
},
{
actions: {
setAccounts: assign({
accounts: (_, event) => event.data
}),
setAccountCandidate: assign({
candidateAccount: (_, event) => event.data
}),
sendSetAccountCandidate: send((_, event) => ({
type: "SET_ACCOUNT_CANDIDATE",
data: event.data
})),
setTransactions: assign({
transactions: (_, event) => event.data
}),
setDefaultAccountCandidate: assign({
candidateAccount: context => context.selectedAccount
})
},
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment