Skip to content

Instantly share code, notes, and snippets.

@elsangedy
Created November 30, 2020 11:13
Show Gist options
  • Save elsangedy/d6bd597cbbd7b5fe7fcf7ce45819df51 to your computer and use it in GitHub Desktop.
Save elsangedy/d6bd597cbbd7b5fe7fcf7ce45819df51 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const fetchMachine = Machine({
initial: 'images',
context: {
images: [],
expenses: [],
category: undefined
},
states: {
images: {
on: {
SKIP: 'category',
SELECT: 'uploading',
EXPENSES: 'expenses'
}
},
uploading: {
invoke: {
src: 'upload',
onDone: [
{
cond: 'hasCategory',
target: 'expense',
actions: ['addImages']
},
{
target: 'category',
actions: ['addImages']
}
],
onError: {
target: 'images'
}
}
},
category: {
on: {
BACK: 'images',
SELECT: {
target: 'expense',
actions: ['setCategory']
}
}
},
expense: {
on: {
BACK: {
target: 'category',
actions: ['removeCategory']
},
ADD_IMAGES: 'images',
SUBMIT: 'submitting_expense'
}
},
submitting_expense: {
invoke: {
src: 'submitExpense',
onDone: {
target: 'expense_confirmation',
actions: ['addExpense']
},
onError: {
target: 'expense'
}
}
},
expense_confirmation: {
on: {
CONTINUE: 'expenses',
ADD_MORE: 'images'
}
},
expenses: {
on: {
BACK: 'images',
SUBMIT: 'claim'
}
},
claim: {
on: {
SUBMIT: 'submitting_claim'
}
},
submitting_claim: {
invoke: {
src: 'submitClaim',
onDone: {
target: 'images',
actions: ['reset']
},
onError: {
target: 'claim'
}
}
}
}
}, {
guards: {
hasCategory: (context, envent) => {
return !!context.category
}
},
actions: {
addImages: assign({
images: (context, event) => {
return [
...context.images,
...event.data
]
}
}),
addExpense: assign({
images: [],
category: undefined,
expenses: (context, event) => {
return [
...context.expenses,
event.data
]
}
}),
setCategory: assign({
category: (context, event) => {
return event.data || 'fake-category'
}
}),
removeCategory: assign({
category: undefined
}),
reset: assign({
images: [],
expenses: [],
category: undefined
})
},
services: {
upload: () => {
return new Promise(resolve => {
setTimeout(() => {
resolve([`image-${Math.random()}`])
}, 1000)
})
},
submitExpense: () => {
return new Promise(resolve => {
setTimeout(() => {
resolve({
id: `expense-${Math.random()}`
})
}, 1000)
})
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment