Next.js Discord

Discord Forum

Hydrating Client Side State with Server State - Redux Toolkit

Unanswered
Least Bittern posted this in #help-forum
Open in Discord
Avatar
Least BitternOP
New to Redux and currently trying to implement it into an existing Next.js project using Redux Toolkit and Next Redux.

In getServerSideProps I call some actions to update the values in the store which I'd like to persist client side.


Per the Next-Redux-Wrapper docs, I've added an extra reducer to my slice to merge Client and Server State which looks like:

extraReducers: {
    [HYDRATE]: (state, action) => {
      state.val = [...state, action.payload.value.val]
    }
}


However, when I try to access the store in my page component I get the initial/empty state.

export const getServerSideProps = () => {
  console.log(store.getState().value.val) // => [foo, bar]
}


const Page = () => {
  console.log(store.getState().value.val) // => []
}


Any initial thoughts as to why this is happening? Or am I misunderstanding the HYDRATE action such that it will only merge Client State => Server State and not the other way around?

1 Reply

Avatar
If you are using page dir then the next-redux-wrapper package is a good solution to hydrate the state between server and client. https://github.com/kirill-konshin/next-redux-wrapper