UNPKG

@gravitywelluk/react-hooks

Version:
59 lines (58 loc) 2.47 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.usePagination = void 0; const react_1 = require("react"); const reducer = (state, action) => { var _a, _b, _c; if (action.type === "next") { return Object.assign(Object.assign({}, state), { offset: state.offset + state.limit }); } else if (action.type === "previous") { const canGoBack = state.offset >= state.limit; return Object.assign(Object.assign({}, state), { offset: canGoBack ? state.offset - state.limit : state.offset }); } else if (action.type === "setPageSize" && ((_a = action.payload) === null || _a === void 0 ? void 0 : _a.limit)) { return Object.assign(Object.assign({}, state), { offset: 0, limit: action.payload.limit }); } else if (action.type === "sort") { return Object.assign(Object.assign({}, state), { offset: 0, order: (_b = action.payload) === null || _b === void 0 ? void 0 : _b.order }); } else if (action.type === "filter") { return Object.assign(Object.assign({}, state), { offset: 0, filters: (_c = action.payload) === null || _c === void 0 ? void 0 : _c.filters }); } else if (action.type === "reset" && action.payload) { return action.payload; } return state; }; /** Custom reducer to handle offset-based pagination of API endpoints in React */ // eslint-disable-next-line @typescript-eslint/ban-types const usePagination = (initialState) => { const [paginationState, dispatch] = (0, react_1.useReducer)(reducer, initialState); // useRef ensures that paginationActions remains stable, avoiding useEffect loops when calling these actions const paginationActions = (0, react_1.useRef)({ next: () => dispatch({ type: "next" }), previous: () => dispatch({ type: "previous" }), setPageSize: pageSize => dispatch({ type: "setPageSize", payload: { limit: pageSize } }), sort: order => dispatch({ type: "sort", payload: { order: order || undefined } }), filter: filters => dispatch({ type: "filter", payload: { filters: filters || undefined } }), reset: () => dispatch({ type: "reset", payload: initialState }) }); return { params: paginationState, actions: paginationActions.current }; }; exports.usePagination = usePagination;