2022/03/28 React 새로고침하면 state값이 사라지는 문제
2022. 3. 28. 23:45ㆍProject : 근의 공식(Muscle Formula)/Error Handling
Redux로 관리하든 그렇지 않든 React의 State값(소위 상태값)들은 새로고침할 시 초기화되는 문제가 있다.
이 문제를 해결하는 간단한 방법은 localStorage에 값을 저장하여 필요할 때 빼서 쓰고, 그렇지 않을 시 삭제하는 것이다.
1. dispatch로 login/logout할 때 Reducer에서 state값 변경 외에 localStorage에도 값을 저장/삭제한다.
export const userInfoReducer = createSlice({
name: 'userInfo',
initialState: initialState,
reducers: {
LOG_IN : (state, action: PayloadAction<{id: number, nickname: string, image: string}>) => {
state.userInfo = action.payload;
state.isLogin = true;
//localStorage에도 저장
localStorage.setItem('userInfo', JSON.stringify(action.payload));
localStorage.setItem('isLogin', JSON.stringify(true));
},
LOG_OUT : state => {
state.userInfo = {id: '', nickname: '', image: ''};
state.isLogin = false;
//localStorage에서도 삭제
localStorage.removeItem('userInfo');
localStorage.removeItem('isLogin');
},
}
})
export const {LOG_IN, LOG_OUT} = userInfoReducer.actions;
export default userInfoReducer.reducer
2. 상태값이 필요한 컴포넌트에서 useSelector로 상태값을 불러오고 그 상태값에 TS narrowing한 localStorage의 값을 할당한다.
let user = useSelector((state: RootState) => state.userInfo.userInfo);
let isLogin = useSelector((state: RootState) => state.userInfo.isLogin);
const localUser = localStorage.getItem('userInfo');
const localLogin = localStorage.getItem('isLogin');
if (localUser !== null ) {
user = JSON.parse(localUser);
};
if (localLogin !== null) {
isLogin = JSON.parse(localLogin);
}
그러면 새로고침해도 상태가 초기화되지 않는다. (localStorage에 있는 값을 가져오기 때문).
간단히 해결했지만 보안상으론 어떤 결과를 초래할지...
교훈 : 로그아웃을 꼭 합시다.
'Project : 근의 공식(Muscle Formula) > Error Handling' 카테고리의 다른 글
| 2022/03/24 TS 리액트로 Props 전달 문제 (0) | 2022.03.24 |
|---|---|
| 2022/03/23 img 태그 속성 읽어오기 event.currentTarget (0) | 2022.03.23 |
| 2022/03/22 styled-component에서 :checked가 안될 때 (0) | 2022.03.22 |
| 2022/03/22 별점 input 태그 쓰기와 value 가져오기 (0) | 2022.03.22 |
| 2022/03/23 TS 리액트에서 event 타입 지정 (2) | 2022.03.20 |