Skip to content

Instantly share code, notes, and snippets.

@nullmastermind
Last active June 30, 2021 17:27
Show Gist options
  • Save nullmastermind/eee925e8c4325bdedde59d92b7488265 to your computer and use it in GitHub Desktop.
Save nullmastermind/eee925e8c4325bdedde59d92b7488265 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 limit = 24;
const canPrev = ({page}) => page > 0;
const canNext = ({page, total}) => page*limit < total;
const isProductEmpty = ({total}) => total===0;
const hasProduct = ({total}) => total>0;
const fetchMachine = Machine({
id: 'fetch',
initial: 'initial',
context: {
page: 0,
keyword: '',
products: [],
total: 0
},
states: {
initial: {
on: {
FETCH: {
target: 'product_loading',
}
}
},
product_loading: {
on: {
RESOLVE: [
{
target: 'product_success',
actions: assign({
product: (context) => context.product = [],
total: (context) => context.total = 10,
}),
cond: hasProduct
},
{
target: 'product_empty',
actions: assign({
product: (context) => context.product = [],
total: (context) => context.total = 0,
}),
cond: isProductEmpty
}
],
REJECT: 'product_failure'
}
},
product_success: {
on: {
NEXT_PAGE: {
target: 'product_loading',
actions: assign({
page: (context) => context.page+1
}),
cond: canNext
},
PREV_PAGE: {
target: 'product_loading',
actions: assign({
page: (context) => context.page-1
}),
cond: canPrev
},
SEARCH: {
target: 'product_loading',
actions: assign({
keyword: (context) => context.keyword = 'something',
page: (context) => context.keyword = 0,
})
}
}
},
product_empty: {
on: {
SEARCH: {
target: 'product_loading',
actions: assign({
keyword: (context) => context.keyword = 'something',
page: (context) => context.keyword = 0,
})
}
}
},
product_failure: {
on: {
RETRY: {
target: 'product_loading',
}
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment