46 lines
1020 B
TypeScript
46 lines
1020 B
TypeScript
/* eslint-disable sonarjs/no-small-switch */
|
|
import type { LdapUser } from '@/types/user';
|
|
import type { PropsWithChildren } from 'react';
|
|
import { createContext, useMemo, useReducer } from 'react';
|
|
|
|
type State = {
|
|
step: 'login' | 'telegram';
|
|
user: LdapUser | undefined;
|
|
};
|
|
|
|
type Action = {
|
|
payload: State;
|
|
type: 'set-step';
|
|
};
|
|
|
|
const reducer = (state: State, action: Action): State => {
|
|
switch (action.type) {
|
|
case 'set-step':
|
|
return {
|
|
...state,
|
|
...action.payload,
|
|
};
|
|
|
|
default:
|
|
return state;
|
|
}
|
|
};
|
|
|
|
type Context = {
|
|
dispatch: React.Dispatch<Action>;
|
|
state: State;
|
|
};
|
|
|
|
export const FormStateContext = createContext<Context>({} as Context);
|
|
|
|
export function FormStateProvider({ children }: PropsWithChildren) {
|
|
const [state, dispatch] = useReducer(reducer, {
|
|
step: 'login',
|
|
user: undefined,
|
|
});
|
|
|
|
const value = useMemo(() => ({ dispatch, state }), [state]);
|
|
|
|
return <FormStateContext.Provider value={value}>{children}</FormStateContext.Provider>;
|
|
}
|