| 123456789101112131415161718192021222324252627282930313233343536 |
- import {Dispatch, useReducer} from 'react';
- import {createContext} from 'use-context-selector';
- export type TableSearchAction<S> = {type: 'SEARCH', payload: S} | {type: 'RESET'};
- type InitStateType = Readonly<Record<string, unknown>>;
- export function useTableSearchContextReducer<S extends InitStateType>(init: S) {
- function initState() {
- return {...init};
- }
- function reducer(state: S, action: TableSearchAction<S>): S {
- const {type} = action;
- switch (type) {
- case 'SEARCH':
- return action.payload;
- case 'RESET':
- return initState();
- default:
- return state;
- }
- }
- return useReducer(reducer, initState());
- }
- export type TableSearchContext<S> = [S, Dispatch<TableSearchAction<S>>];
- export function createTableSearchContext<S extends InitStateType>(state: S) {
- return createContext<TableSearchContext<S>>([
- {...state},
- () => null,
- ]);
- }
|