Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {createContext, Dispatchm useReducer} from 'react';
- import User from '../model/User';
- interface State {
- user?: User;
- specialAwesomeFeature: boolean;
- }
- type Action =
- | {type: 'SET_USER'; user?: User}
- | {type: 'SET_FEATURE'; allowed: boolean}
- interface Context {
- state?: State;
- dispatch?: Dispatch<Action>;
- }
- function reducer(state: State, action: Action) {
- switch (action.type) {
- case 'SET_USER':
- return {...state, user: action.user};
- case 'SET_FEATURE':
- return {...state, specialAwesomeFeature: action.allowed};
- default:
- return {...state};
- }
- }
- const initialState: State = {user: null, specialAwesomeFeature: false};
- export const AuthContext = createContext<Context>({});
- export const AuthProvider = ({children, initialState: overrideInitialState}) => {
- const [state, dispatch] = useReducer(reducer, overrideInitialState || initialState);
- return <AuthContext.Provider value={{state, dispatch}}>{children}</AuthContext.Provider>;
- };
- export const setUser = (user?: User): Action => ({type: 'SET_USER', user: user});
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement