Next.jsにReduxを導入するとき、SSR中にデータをフェッチしたデータでreduxのstoreを初期化したい
どのページでも毎回やりたいことなので_app.tsx
のgetInitialProps
の中で行う
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> ); }