react-next-boilerplate icon indicating copy to clipboard operation
react-next-boilerplate copied to clipboard

dispatching from getInitialProps

Open alexgrot opened this issue 5 years ago • 2 comments

is it possible to dispatch actions from getInitialProps to prefill redux store before client gets the server side rendered page with this configuration of the redux store?

is there a pattern to do this?

since the redux store in the appContext of the src/pages/_app.js is empty, i tried to add the src/containers/Home/reducer and -/saga in src/utils/configure-store.js

store.injectedReducers = { homeReducer };
store.injectedSagas = { homeSaga };

to have something i can test this with.

injecting reducer and saga works and i can see that the homeReducer and homeSaga are injected in the ctx-object of the src/pages/index.js when rendered server side in console.

IndexPage.getInitialProps = async ctx => {
  console.log(ctx.reduxStore);

gives me:

{
  dispatch: [Function],
  subscribe: [Function: subscribe],
  getState: [Function: getState],
  replaceReducer: [Function: replaceReducer],
  runSaga: [Function],
  injectedReducers: { homeReducer: [Function: showcasesReducer] },
  injectedSagas: { homeSaga: [GeneratorFunction: dataShowcases] },
  [Symbol(observable)]: [Function: observable]
}

but i dont have any luck figuring out how to dispatch an action from there properly. my guess is that the page needs to be connected in some way as well but since your setup is different from the with-redux-saga example from the official nextjs repo, i cant really figure out how to properly do this.

what i basically want to do is: dispatch (for e.g.) the getShowcases() action on the server so that the client gets the fully rendered page including the data fetched in saga.

thanks for reading, awesome project :)

alexgrot avatar Apr 23 '20 01:04 alexgrot

@alexgrot Thanks for creating the issue. I am very happy that you like the project.

I would like to do some tests before answering your question

wootsbot avatar Apr 23 '20 03:04 wootsbot

@alexgrot The work leaves me little time, but I am very aware of your problem.

If you have found a way or were able to solve your own question, suggestions or PRS are welcome.

wootsbot avatar Apr 30 '20 01:04 wootsbot