redux를 새로고침해도 유지하자 (redux-persist)

이창호·2022년 5월 26일
0
post-thumbnail

스토어의 정보들이 새로고침 하면서 날아가는 이슈가 있었는데 이를 간단히 해결할 수 있는 redux-persist가 있다고 해서 알아보았어요.

  • 설치
npm install redux-persist
  • persist 정의하기
// store/index

import { persistReducer } from "redux-persist"; // load
import storageSession from "redux-persist/lib/storage/session";  // sessionStorage
// import storage from 'redux-persist/lib/storage // localstorage

const persistConfig: any = {
  key: "root",
  storage: storageSession, // 사용할 스토리지를 정의해요.
  whitelist: ["authReducer"], // 유지 할 데이터를 정의해요
  blacklist // 제외 할 데이터를 정의해요
};


const persistedReducer = persistReducer(persistConfig, reducer);
// reducer와 위에서 설정 한 persist설정을 합쳐요
  • persist 적용하기
import store from "./store";
import { Provider } from "react-redux";

import { persistStore } from "redux-persist"; // load
import { PersistGate } from "redux-persist/integration/react"; // load

const persistor = persistStore(store); // 정의

ReactDOM.render(
  <Provider store={store}>
    <PersistGate persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>,

진행중인 프로젝트의 라우터는 스토어에 auth의 데이터를 가져와서 그 데이터의 유/무에 따라 redirect를 한다던가 권한이 있는 메뉴만 접근하게 하는 등 유저정보들을 필요로 하는데,

persist를 사용을 하지 않는다면 새로고침 후 스토어에 데이터가 없어서 접근이 안되게 되어있는데 persist를 사용 후 데이터를 유지 시켜줄 수 있어서 편리해요

profile
조금씩 나아지기

0개의 댓글