以下の内容はhttps://uga-box.hatenablog.com/entry/2022/11/24/000000より取得しました。


【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




以上の内容はhttps://uga-box.hatenablog.com/entry/2022/11/24/000000より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14