forked from canada-ca/tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserState.js
More file actions
39 lines (31 loc) · 1.08 KB
/
UserState.js
File metadata and controls
39 lines (31 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import React, { useContext, useReducer } from 'react'
import { object, node } from 'prop-types'
import equal from 'fast-deep-equal'
const UserStateContext = React.createContext()
const { Provider, Consumer } = UserStateContext
export function UserStateProvider({ initialState, children }) {
const reducer = (state, action) => {
switch (action.type) {
case 'LOGIN':
return Object.assign({}, state, action.user)
case 'LOGOUT':
return Object.assign({}, state, action.user)
default:
return state
}
}
const [state, dispatch] = useReducer(reducer, initialState)
const userState = {
currentUser: state,
isLoggedIn: () => !equal(state, initialState),
login: (user) => dispatch({ type: 'LOGIN', user }),
logout: () => dispatch({ type: 'LOGOUT', user: initialState }),
}
return <Provider value={userState}>{children}</Provider>
}
UserStateProvider.propTypes = {
initialState: object.isRequired,
children: node.isRequired,
}
export const UserState = Consumer
export const useUserState = () => useContext(UserStateContext)