본문 바로가기
Coding/Redux

Redux - next.js store에 접근

by z쿳쿳z 2021. 10. 16.
728x90
반응형

redux와 next.js를 같이 사용하고 있다면....

SSR이 되면서 초기 data를 받아온 것을 redux에 넣어 뿌려줘야 하지만 next js에 나와있는 getServerSideProps만으로는 redux store에 접근할 수 없다.

store 접근
store console 결과

#object

   * next getServerSideProps 에서 store 접근

 

## next-redux-wrapper 7.0 이하 버전

이와 더불어 추가로 설정을 더 해줘야 store 접근 할 수 있다.

redux store를 setting 하면서 wrapper를 export를 해줄텐데 여기서 wrapper를 가져와서 사용하면 store에 접근을 할 수 있다.

export const getServerSideProps = wrapper.getServerSideProps()

store 접근
store console 결과
redux store

 

그리고 _app.tsx에 wrapper.withRedux로 component를 감싸야 한다.

import type { AppProps } from "next/app";
import wrapper from "../redux/store";

function MyApp({ Component, pageProps }: AppProps) {
   //...code
}

export default wrapper.withRedux(MyApp);

 

## next-redux-wrapper 7.0 이상 버전

7.0 이상 버전에서는 HOC 형태로 변환이 되었다. 첫번째 callback 인자로 store값을 가져올 수 있다. 

export const getServerSideProps: GetServerSideProps = wrapper.getServerSideProps(
  (store) => async (context: Context) => {
    await store.dispatch(fetchUser());
    return {
      props: {}, // will be passed to the page component as props
    };
  }
);
728x90
반응형