본문 바로가기
React/Next.js

[Next.js] Next.js에서 redux-persist 사용

by 박헹구 2022. 2. 24.
반응형

새로고침하면 리덕스가 초기화 되는 걸 

해결하기 위해서 redux-persist를 사용해서 새로고침해도 리덕스가 초기화 되는 현상을 막아주었다. 

 

우선 redux-persist 모듈을 깔아주고. 아래와 같이 설정해주었다. 

yarn add redux-persist

or

npm install redux-persist
//persistMiddleware.ts

import { REHYDRATE } from 'redux-persist/lib/constants';
import { Middleware } from 'redux';

const persistMiddleware: Middleware = (store) => (dispatch) => async (
    action,
) => {
    if (action.type === REHYDRATE && action.key === 'root') {
        console.log('root REHYDRATE');
        dispatch(action);
    } else {
        dispatch(action);
    }
};

export default persistMiddleware;
//store.ts
...
const persistedReducer = persistReducer(persistConfig, reducer);

const storeConfig : ConfigureStoreOptions<AppState, AnyAction,[ThunkMiddleware<AppState, AnyAction>]> = {
  reducer: persistedReducer,
  middleware,
  swrMiddleware,
};
export const store = configureStore(storeConfig);

...
//_app.tsx

...
const persistor = persistStore(store);

export default function App({ Component, pageProps }: AppProps) {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <Layout>
          <Component {...pageProps} />
        </Layout>
      </PersistGate>
    </Provider>
  );
}​

 

반응형

댓글