Skip to content

Instantly share code, notes, and snippets.

@elsangedy
Last active September 16, 2019 13:30
Show Gist options
  • Save elsangedy/4562d68f1e733c13cc74cf2104a83f50 to your computer and use it in GitHub Desktop.
Save elsangedy/4562d68f1e733c13cc74cf2104a83f50 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const fetchMachine = Machine({
id: "infinite-scroll",
initial: "idle",
context: {
page: 1,
size: 2,
total: 0,
keyword: "",
items: []
},
states: {
idle: {
on: {
SEARCH: {
target: "searching",
actions: assign({ page: 1, keyword: (_, event) => event.keyword }),
cond: 'notSameKeyword'
},
FETCH_MORE: {
target: "fechingMore",
cond: "hasMore",
actions: assign({ page: context => context.page + 1 })
}
}
},
searching: {
invoke: {
id: "search",
src: "onFetch",
onDone: {
target: "idle",
actions: assign((_, event) => event.data)
},
onError: {
target: "idle"
}
}
},
fechingMore: {
invoke: {
id: "fetchMore",
src: "onFetch",
onDone: {
target: "idle",
actions: assign((context, event) => ({
...event.data,
items: [...context.items, ...event.data.items]
}))
},
onError: {
target: "idle"
}
}
}
}
},
{
guards: {
hasMore: (context, event) => {
return context.page < Math.ceil(context.total / context.size);
},
notSameKeyword: (context, event) => {
return context.keyword !== event.keyword
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment