6500db9c1c
* move index to home folder, create state and context files and barrell folder * Sanity Check Commit: reducer added to home.tsx manual QA all working * WIP: promptBar * fix missing json parse on folders and prompts * split context and add promptbar context * add context to nested prompt componets and componetize Folder componet * remove log * Create buttons folder and componetize sidebar action button * tidy up prompt handlers * componetized sidebar * added back chatbar componet to left side sidebar * monster commit: Componetized the common code between chatbar and promptbar into new componet Sidebar and added context to both bars * add useFetch service * added prettier import sort to keep imports ordered and easier to indentify * added react query and useFetch to work with RQ * added apiService, errorService and reactQuery * add callback and tidy up error service * refactor chat and child componets to useContext * fix extra calls and bad calls to mel endpoint * minor import cleanup --------- Co-authored-by: jc.durbin <jc.durbin@ardanis.com>
31 lines
995 B
TypeScript
31 lines
995 B
TypeScript
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]);
|
|
};
|