App.js
const App = () => {
const dispatch = useDispatch();
useEffect(() => {
const unsubscribe = onAuthStateChangedListener((user) => {
if (user) {
createUserDocumentFromAuth(user);
}
dispatch(setCurrentUser(user));
});
return unsubscribe;
}, []);
user.action.js
export const setCurrentUser = (user) =>
createAction(USER_ACTION_TYPES.SET_CURRENT_USER, user);
reducer.utils.js
const createAction = (type, payload) => ({ type, payload })
user.reducer.js
const INITIAL_STATE = {
currentUser: null,
};
export const userReducer = (state = INITIAL_STATE, action) => {
const { type, payload } = action;
switch (type) {
case USER_ACTION_TYPES.SET_CURRENT_USER:
return {
...state,
currentUser: payload,
};
default:
return state;
}
};
- 여기까지가 dispatch 를 통해 currentUser를 업데이트하는 과정
navigation.component.js
import { selectCurrentUser } from "../../store/user/user.selector";
const Nav = () => {
const currentUser = useSelector(selectCurrentUser);
...
user.selector.js
export const selectCurrentUser = (state) => state.user.currentUser;
useSelector hook을 사용하여 store내부(store => user => currentUser)의 값에 접근할 수 있다.
유익한 글이었습니다.