UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【Next.js】SSR中にデータをフェッチしたものでreduxのstoreを初期化する

Next.jsにReduxを導入するとき、SSR中にデータをフェッチしたデータでreduxのstoreを初期化したい

どのページでも毎回やりたいことなので_app.tsxgetInitialPropsの中で行う

getInitialPropsはサーバー上で実行される

この中で、データフェッチを行いstoreを初期化する

MyApp.getInitialProps = async (appContext: AppContext) => {
  const appProps = await App.getInitialProps(appContext);
  const ctx = appContext.ctx;
  const reduxStore = initialiseStore({});
  const { dispatch } = reduxStore;
  const res = await fetch('/path/to/api/endpoint/');
  const json = await res.json();
  await dispatch(setData(json));

  appProps.pageProps = {
    ...appProps.pageProps,
    initialReduxState: reduxStore.getState(),
  };
  return appProps;
};

そして、MyAppコンポーネントでstoreを受け取り、Providerにセットすることで初期化が完了する

function MyApp({ Component, pageProps }: AppProps) {
  const reduxStore = createStore(pageProps.initialReduxState);
  return (
      <Provider store={reduxStore}>
          <Component {...pageProps} />
      </Provider>
  );
}

参考

www.quintessential.gr