From e32aeb1b3d3b8e9a3b3fb4918e41306f0c55d779 Mon Sep 17 00:00:00 2001 From: Adam Rybinski Date: Mon, 1 Nov 2021 16:34:39 +0100 Subject: [PATCH] Create paginationMachine.js --- paginationMachine.js | 71 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 paginationMachine.js diff --git a/paginationMachine.js b/paginationMachine.js new file mode 100644 index 0000000..a82fe53 --- /dev/null +++ b/paginationMachine.js @@ -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;