bjoluc / next-redux-cookie-wrapper

Sync a subset of your Redux state with cookies in Next.js :cookie: :sparkles:
MIT License
114 stars 4 forks source link

Cookies not being stored properly? state undefined #2

Closed remjx closed 4 years ago

remjx commented 4 years ago

I followed the installation instructions but it is not working. When I refresh page after changing redux state, the state is lost.

I only have one additional cookie with name="reduxPersistIndex" and value="[%22persist:root%22]". This does not look right?

The 1. 3. and 4. log outputs from debug mode look OK to me. This is expected since next-redux-wrapper is working fine, and these are logs from that. However the additional logs seem to indicate something is wrong.

0. Extracting state from cookies (if any)
0. Got state undefined

Any idea why it would be coming back undefined?

Snippet from my _app.js:

MyApp.getInitialProps = async ({ Component, ctx}) => {
  const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {};
  return {pageProps};
}

export default withReduxCookiePersist(makeStore)(MyApp);

versions: next @9.2.1 next-redux-cookie-wrapper @1.0.1 redux @4..0.4

If additional information is needed please let me know...

Thanks!

bjoluc commented 4 years ago

Any idea why it would be coming back undefined?

The redux persist cookie storage adapter usually sets two cookies: reduxPersistIndex = [%22persist:root%22] and persist%3Aroot = {serialized state goes here}. Somehow your persist%3Aroot cookie gets not set by the client, which, on the server side, makes the cookie storage adapter fail at parsing the state from the cookies. That's why it sets the initial state to undefined.

I just installed the same versions as you did and unfortunately wasn't able to reproduce the issue. Maybe your state is too large for a cookie? You could try using the whitelist option for a reducer of your choice and see whether the state cookie gets set then.

remjx commented 4 years ago

Thanks, that was the issue. When I whitelisted my smallest redux ruducer, it started working.

The docs do state

You should aim to persist as little state as possible because the cookies' Redux state is included in every request and cookies have a size limit.

It would be nice if there was an error generated if it tried to set a cookie that was too large, but I'm OK with just making sure my state that needs to be persisted is very small to begin with. I see there are other Redux Persist adapters for localStorage, etc so if I really need more I could look that route.

Thank you!!