Skip to content

Instantly share code, notes, and snippets.

@arturcarvalho
Created May 5, 2021 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arturcarvalho/417f16e87b4ce6e7e83d729eefdf06dd to your computer and use it in GitHub Desktop.
Save arturcarvalho/417f16e87b4ce6e7e83d729eefdf06dd to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const infiniteScrollMachine = Machine(
{
id: 'infiniteScroll',
initial: 'fetchingRowOfData',
context: {
totalEntries: Infinity,
data: [],
},
states: {
fetchingRowOfData: {
on: {
RECEIVED_DATA: {
target: 'checkingIfThereIsMoreData',
actions: ['assignDataToContext'],
},
},
invoke: {
src: 'fetchRowOfData',
onError: {
target: 'idle',
actions: 'assignErrorMessageToContext',
},
},
},
idle: {
exit: ['clearErrorMessage'],
on: {
SCROLL_TO_BOTTOM: 'fetchingRowOfData',
},
},
checkingIfThereIsMoreData: {
always: [
{
cond: 'thereIsMoreData',
target: 'idle',
},
{
target: 'noMoreDataToFetch',
},
],
},
noMoreDataToFetch: {
type: 'final',
},
},
},
{
guards: {
thereIsMoreData: (context) => {
return context.totalEntries > context.data.length;
},
},
services: {
fetchRowOfData: () => (send) => {},
},
actions: {
assignDataToContext: assign((context, event) => {
if (event.type !== 'RECEIVED_DATA') return {};
return {
data: [...context.data],
totalEntries: event.totalEntries,
};
}),
clearErrorMessage: assign((context) => ({
errorMessage: undefined,
})),
assignErrorMessageToContext: assign((context, event) => {
return {
errorMessage: event?.data?.message || 'An unknown error occurred',
};
}),
},
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment