221207 항해99 31일차 Redux-persist

요니링 컴터 공부즁·2022년 12월 7일
0
  • 새로고침 시에도 리덕스 내의 데이터를 유지하는 방법
yarn add redux-persist //설치

reducer에 persist store 정의

  • localStorage에 저장하고 싶으면 import storage from 'redux-persist/lib/storage
  • session Storage에 저장하고 싶으면 import storageSession from 'redux-persist/lib/storage/session
// reducers/index.js
import { combineReducers } from "redux";
import { persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";

import auth from "./auth";
import board from "./board";
import studio from "./studio";

const persistConfig = {
  key: "root",
  // localStorage에 저장
  storage,
  // auth, board, studio 3개의 reducer 중에 auth reducer만 localstorage에 저장
  whitelist: ["auth"]
  // blacklist -> 그것만 제외
};

export const rootReducer = combineReducers({
  auth,
  board,
  studio
});

export default persistReducer(persistConfig, rootReducer);

persist store 사용

// src/index.js

import React from "react";
import ReactDOM from "react-dom";
import { createStore, applyMiddleware, compose } from "redux";
import { Provider } from "react-redux";
import { persistStore } from "redux-persist";
import { PersistGate } from "redux-persist/integration/react";
import App from "./App";
import configureStore from "./store";
import { rootReducer } from "./reducers";

const store = createStore(rootReducer);
const persistor = persistStore(store);

const Root = () => (
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>
);

ReactDOM.render(<Root />, document.getElementById("root"));

참조:
redux-persist 사용법

0개의 댓글