question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Issue with Next.js SSR (dispatching actions in getinitialprops) and persisting state

See original GitHub issue

Hi folks, thanks for the great work on the library !! 😃

I am having some trouble when dispatching an action in getInitialProps with my store model defined with persist(store). The store seems to ignore the actions dispatched in getInitialProps and keep the old state. These actions include thunks (async calls).

I defined my model like this: const model = persist( { data, user, UI })

getInitialProps, which works fine without persist, does something like this:

Resources.getInitialProps = async function(context) {    
try {
    const resource = context.query.resource
    const store = context.reduxStore
    await store.dispatch.data.fetchResources(resource)
    const storeResources = await store.getState().data
    let podcasts= storeResources.podcasts
    return{
        podcasts,
    }
    } catch (error) {
        console.log (error)
        return{
            podcasts,
        }
    }
}

The actions dispatched in getInitialProps actually happen, as the variable podcasts is the expected one. They seem to be whipped out though.

My _app.js is:

  static async getInitialProps({ Component, ctx }) {


    const { reduxStore } = ctx

    const isClient = typeof window !== 'undefined'
      if (isClient){
      const token = Cookie.get('FBIdToken')
      if (token) {
        const decodedToken = jwtDecode(token)
        console.log(decodedToken)
        if (decodedToken.exp * 1000 < Date.now()) {
          reduxStore.dispatch.user.logoutUser()
          console.log ('token expired! Log out')
        }
        else {
          reduxStore.dispatch.user.setAuthenticated()
        }
      }
    }


    const pageProps = Component.getInitialProps
      ? await Component.getInitialProps(ctx)
      : {}

    return { pageProps }
  } 
  render() {
    const { Component, pageProps, reduxStore } = this.props
    return (
      <StoreProvider store={reduxStore}> 
        <Component reduxStore={reduxStore} {...pageProps} />
      </StoreProvider>
    )
  }
}

export default withReduxStore(MyApp)

Could anyone give me some guidance?? Thanks!!

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
ctrlplusbcommented, Dec 5, 2019

I believe it will be a simple matter of typeof window === 'undefined' 😃

https://github.com/ctrlplusb/easy-peasy/blob/8514ad3ecfafd541fc8261b4468a494427496fbd/src/helpers.js#L49

export const persist = (model, config) => {
  // if we are not running in a browser context this becomes a no-op
  return typeof window === 'undefined' ? model : {
    ...model,
    [persistSymbol]: config,
  };
};
1reaction
gabrilatorcommented, Apr 13, 2020

No worries, @ctrlplusb ! Managed to do the change you mentioned and it works!

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to integrate Redux — with Next.js and SSR
In this article, we are going to discuss how we can setup redux, and particularly Redux Toolkit, so that the application state will...
Read more >
NEXT.JS with persist redux showing unexpected behaviour
My working store in Next.js app. Try to fix your store. store.js import { createWrapper } from 'next-redux-wrapper'; ...
Read more >
Server-Side Rendered App with Next.js, React and Redux
create a fresh, new Redux store instance on every request;; optionally dispatch some actions;; pull the state out of store;; and then pass...
Read more >
getInitialProps - Data Fetching - Next.js
getInitialProps is used to asynchronously fetch some data, which then populates props . Data returned from getInitialProps is serialized when server rendering, ...
Read more >
Accessing redux state when dispatch called in NextJS ...
static async getInitialProps ({ store }) { await store.dispatch(fetchProducts()) return { products: getProducts(store.getState()) } }. cyberwombat 34648.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found