Advertisement
Guest User

Untitled

a guest
May 27th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. import {createContext, Dispatchm useReducer} from 'react';
  2.  
  3. import User from '../model/User';
  4.  
  5. interface State {
  6. user?: User;
  7. specialAwesomeFeature: boolean;
  8. }
  9.  
  10. type Action =
  11. | {type: 'SET_USER'; user?: User}
  12. | {type: 'SET_FEATURE'; allowed: boolean}
  13.  
  14. interface Context {
  15. state?: State;
  16. dispatch?: Dispatch<Action>;
  17. }
  18.  
  19. function reducer(state: State, action: Action) {
  20. switch (action.type) {
  21. case 'SET_USER':
  22. return {...state, user: action.user};
  23. case 'SET_FEATURE':
  24. return {...state, specialAwesomeFeature: action.allowed};
  25. default:
  26. return {...state};
  27. }
  28. }
  29.  
  30. const initialState: State = {user: null, specialAwesomeFeature: false};
  31.  
  32. export const AuthContext = createContext<Context>({});
  33.  
  34. export const AuthProvider = ({children, initialState: overrideInitialState}) => {
  35. const [state, dispatch] = useReducer(reducer, overrideInitialState || initialState);
  36.  
  37. return <AuthContext.Provider value={{state, dispatch}}>{children}</AuthContext.Provider>;
  38. };
  39.  
  40. export const setUser = (user?: User): Action => ({type: 'SET_USER', user: user});
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement