index.ts 917 B

123456789101112131415161718192021222324252627282930313233343536
  1. import {Dispatch, useReducer} from 'react';
  2. import {createContext} from 'use-context-selector';
  3. export type TableSearchAction<S> = {type: 'SEARCH', payload: S} | {type: 'RESET'};
  4. type InitStateType = Readonly<Record<string, unknown>>;
  5. export function useTableSearchContextReducer<S extends InitStateType>(init: S) {
  6. function initState() {
  7. return {...init};
  8. }
  9. function reducer(state: S, action: TableSearchAction<S>): S {
  10. const {type} = action;
  11. switch (type) {
  12. case 'SEARCH':
  13. return action.payload;
  14. case 'RESET':
  15. return initState();
  16. default:
  17. return state;
  18. }
  19. }
  20. return useReducer(reducer, initState());
  21. }
  22. export type TableSearchContext<S> = [S, Dispatch<TableSearchAction<S>>];
  23. export function createTableSearchContext<S extends InitStateType>(state: S) {
  24. return createContext<TableSearchContext<S>>([
  25. {...state},
  26. () => null,
  27. ]);
  28. }