Spaces:
Paused
Paused
Download hooks/useCreateReducer.ts from matthoffner/chatbot: direct link, hf CLI and curl.
- Browser
- Download file 995 Bytes
-
https://huggingface.co/spaces/matthoffner/chatbot/resolve/fd7f787b285812b649560130c30cee3feb73f057/hooks/useCreateReducer.ts
- Command line
-
hf download hf://spaces/matthoffner/chatbot@fd7f787b285812b649560130c30cee3feb73f057/hooks/useCreateReducer.ts
-
curl -L -o useCreateReducer.ts https://huggingface.co/spaces/matthoffner/chatbot/resolve/fd7f787b285812b649560130c30cee3feb73f057/hooks/useCreateReducer.ts
995 Bytes
| import { useMemo, useReducer } from 'react'; | |
| // Extracts property names from initial state of reducer to allow typesafe dispatch objects | |
| export type FieldNames<T> = { | |
| [K in keyof T]: T[K] extends string ? K : K; | |
| }[keyof T]; | |
| // Returns the Action Type for the dispatch object to be used for typing in things like context | |
| export type ActionType<T> = | |
| | { type: 'reset' } | |
| | { type?: 'change'; field: FieldNames<T>; value: any }; | |
| // Returns a typed dispatch and state | |
| export const useCreateReducer = <T>({ initialState }: { initialState: T }) => { | |
| type Action = | |
| | { type: 'reset' } | |
| | { type?: 'change'; field: FieldNames<T>; value: any }; | |
| const reducer = (state: T, action: Action) => { | |
| if (!action.type) return { ...state, [action.field]: action.value }; | |
| if (action.type === 'reset') return initialState; | |
| throw new Error(); | |
| }; | |
| const [state, dispatch] = useReducer(reducer, initialState); | |
| return useMemo(() => ({ state, dispatch }), [state, dispatch]); | |
| }; | |