-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.context.jsx
59 lines (45 loc) · 1.46 KB
/
user.context.jsx
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { createContext, useEffect, useReducer } from 'react'
import { authStateChangedListener, createUserDocumentFromAuth } from '../utils/firebase/firebase.utils';
export const UserContext = createContext({
currentUser: null,
setCurrentUser: () => null
})
export const USER_ACTION_TYPES = {
SET_CURRENT_USER: 'SET_CURRENT_USER'
}
const userReducer = (state, action) => {
const {type, payload} = action;
console.log('dispatched');
console.log(action);
switch (type) {
case USER_ACTION_TYPES.SET_CURRENT_USER:
return {
...state,
currentUser: payload
}
default:
throw new Error(`Unhandled type ${type} in userReducer`);
}
}
const INITIAL_STATE = {
currentUser: null
}
export const UserProvider = ({children}) => {
const [ state, dispatch ] = useReducer(userReducer, INITIAL_STATE);
const {currentUser} = state;
console.log(currentUser);
const setCurrentUser = (user) => {
dispatch({ type: USER_ACTION_TYPES.SET_CURRENT_USER, payload: user});
}
const value = { currentUser, setCurrentUser}
useEffect(()=>{
const unsubscribe = authStateChangedListener((user)=>{
if (user) {
createUserDocumentFromAuth(user);
}
setCurrentUser(user);
});
return unsubscribe
},[])
return <UserContext.Provider value={value}>{children}</UserContext.Provider>
}