UNPKG

ra-core

Version:

Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React

104 lines 3.26 kB
import { useReducer, useEffect, useRef, useCallback } from 'react'; import { SORT_ASC, SORT_DESC } from './list/queryReducer'; var sortReducer = function (state, action) { switch (action.type) { case 'SET_SORT': return action.payload; case 'SET_SORT_FIELD': { var field = action.payload; var order = state.field === field ? state.order === SORT_ASC ? SORT_DESC : SORT_ASC : SORT_ASC; return { field: field, order: order }; } case 'SET_SORT_ORDER': { var order = action.payload; if (!state.field) { throw new Error('cannot change the order on an undefined sort field'); } return { field: state.field, order: order, }; } default: return state; } }; export var defaultSort = { field: '', order: 'ASC' }; /** * Set the sort { field, order } * @name setSort * @function * @param {SortPayload} sort the sort object */ /** * Set the sort field, swap the order if the field is the same * @name setSortField * @function * @param {string} field the sort field */ /** * Set the sort order * @name setSortOrder * @function * @param {string} order The sort order, either ASC or DESC */ /** * @typedef SortProps * @type {Object} * @property {Object} sort: the sort object. * @property {string} sort.field: the sort object. * @property {'ASC' | 'DESC'} sort.order: the sort object. * @property {setSort} setSort * @property {setSortField} setSortField * @property {setSortOrder} setSortOrder */ /** * Hooks to provide sort state * * @example * * const { sort, setSort, setSortField, setSortOrder } = useSort({ * field: 'name', * order: 'ASC', * }); * * setSort({ field: 'name', order: 'ASC' }); * // is the same as * setSortField('name'); * setSortOrder('ASC'); * * @param {Object} initialSort * @param {string} initialSort.field The initial sort field * @param {string} initialSort.order The initial sort order * @returns {SortProps} The sort props */ var useSortState = function (initialSort) { if (initialSort === void 0) { initialSort = defaultSort; } var _a = useReducer(sortReducer, initialSort), sort = _a[0], dispatch = _a[1]; var isFirstRender = useRef(true); useEffect(function () { if (isFirstRender.current) { isFirstRender.current = false; return; } dispatch({ type: 'SET_SORT', payload: initialSort }); }, [initialSort.field, initialSort.order]); // eslint-disable-line react-hooks/exhaustive-deps return { setSort: useCallback(function (sort) { return dispatch({ type: 'SET_SORT', payload: sort }); }, [dispatch]), setSortField: useCallback(function (field) { return dispatch({ type: 'SET_SORT_FIELD', payload: field }); }, [dispatch]), setSortOrder: useCallback(function (order) { return dispatch({ type: 'SET_SORT_ORDER', payload: order }); }, [dispatch]), sort: sort, }; }; export default useSortState; //# sourceMappingURL=useSortState.js.map