[react] redux-persist 특정 state만 적용하기

nemo·2022년 10월 7일
0

React

목록 보기
27/28

state를 새로고침 후에도 유지하기 위해 redux-persist를 사용한다. 보통은 reducer를 지정해 전체 state를 유지하지만, 특정 state만 유지하고 싶을 때도 있다. 이때 whitelist와 blacklist 옵션을 같이 사용하면 된다.

reducer의 모든 state에 persist 적용

(reducers/index.ts)

import { combineReducers } from 'redux';
import authReducer from './authReducer';
import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';

const rootPersistConfig = {
  key: "root", // localStorage key 
  storage, // localStorage
  whitelist: ["auth"], // target (reducer name)
}

const rootReducer = combineReducers({
  auth: authReducer
});

export default persistReducer(rootPersistConfig, rootReducer);

특정 state만 persist 적용

(reducers/index.ts)

import { combineReducers } from 'redux';
import authReducer from './authReducer';
import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';

const rootPersistConfig = {
  key: "root", // localStorage key 
  storage, // localStorage
  blacklist: ["auth"], // target (reducer name)
}

const authPersistConfig = {
  key: "auth", // localStorage key 
  storage, // localStorage
  whitelist: ["user"], // target (state name)
}

const rootReducer = combineReducers({
  auth: persistReducer(authPersistConfig, authReducer)
});

export default persistReducer(rootPersistConfig, rootReducer);

0개의 댓글