Skip to content

Commit

Permalink
Create paginationMachine.js
Browse files Browse the repository at this point in the history
  • Loading branch information
adamrybinski authored Nov 1, 2021
1 parent 7d9db9e commit e32aeb1
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions paginationMachine.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { assign, createMachine } from './deps.js';

const infiniteScrollMachine = createMachine({
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, ...event.data],
totalEntries: event.totalEntries
};
}),
clearErrorMessage: assign(context => ({
errorMessage: undefined
})),
assignErrorMessageToContext: assign((context, event) => {
return {
errorMessage: event.data?.message || 'An unknown error occurred'
};
})
}
});
export default infiniteScrollMachine;

0 comments on commit e32aeb1

Please sign in to comment.