• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

(정보 공유)redux toolkit으로 미들웨어 장착하기

23.06.21 10:26 작성 조회수 458

2

import { configureStore } from "@reduxjs/toolkit";
import { createWrapper } from "next-redux-wrapper";
import reducer from "../reducers";

function getServerState() {
  return typeof document !== "undefined"
    ? JSON.parse(document.querySelector("#__NEXT_DATA__").textContent)?.props
        .pageProps.initialState
    : undefined;
}
const loggerMiddleware =
  ({ dispatch, getState }) =>
  (next) =>
  (action) => {
    console.log(action);
    return next(action);
  };
const serverState = getServerState();
console.log("serverState", serverState);
const makeStore = () =>
  configureStore({
    reducer,
    devTools: true,
    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware().concat(loggerMiddleware),
    preloadedState: serverState, // SSR
  });

export default createWrapper(makeStore);

redux toolkit으로 미들웨어를 장착하고 싶으시면 getDefaultMiddleware에 concat으로 장착하시면 됩니다 configureStore코든는 제로초님 깃허브에 있습니다

답변 1

답변을 작성해보세요.

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2023.06.23

안녕하세요, 인프런 AI 인턴입니다.

redux toolkit으로 미들웨어를 장착하고 싶으시면, getDefaultMiddleware 함수를 사용해서 기본적으로 제공하는 미들웨어 배열에 concat 메소드로 추가하시면 됩니다.

위에서 사용된 loggerMiddleware는 next 함수에 action을 전달하기 전과 후에 로그를 출력하는 간단한 미들웨어 함수입니다.

configureStore 함수는 createStore 함수와 비슷한 역할을 하며, createStore 함수보다 더욱 간편하게 스토어를 생성할 수 있습니다.

예제 코드를 보면 preloadedState로 서버사이드 렌더링(SSR)을 구현한 것도 확인할 수 있습니다. 이를 이용하면, 서버에서 미리 렌더링한 상태를 클라이언트에서도 사용할 수 있어, 랜더링 최적화와 관리가 용이해집니다.

감사합니다.