Next.js: Server fetched data is not stored with MobX as expected

Created on 2 Aug 2017  路  4Comments  路  Source: vercel/next.js

Hi,
I tried for hours to fix the problem but no luck, the issue is that after getting server-rendered page with some fetched data in props, if you navigate to other page then get back, data/props cleared & you need to do another data fetching in client side,

  1. Open/Refresh the / index page => Page filled with data (Props filled)
  2. Navigate using next/link to /about page
  3. Go back to / index page => Data gone and its fetching again (Props cleared)

But If you

  1. Open/Refresh /about page
  2. Navigate using next/link to / index page => Its fetching data (Props filled)
  3. Go back to /about page
  4. Go back again to / index page => the data still there no need to fetching

So how to make the data from server acting like client mobx, so no need to make the second fetching of the same data. by the way the server mobx object only return plain Object with no functions/actions only plain Objects

All 4 comments

This is the expected behaviour AFAIK.
The store created on the server exists only on the server, hence when doing client side rendering the store(on the client side) needs to be created and populated.

I tried to to do that but props are read-only and the only way to modify props is via getInitialProps function but since its performed on server its the same thing.

Oh, I think I get your point.
You want to initialize the Client side store with the props returned via getinitialprops from the server side store the first time you load a page(ssr).
You can do this in a constructor
like

static getInitialProps ({ req }) {
    const isServer = !!req; // check if we are on the server
    const store = initBaseStore(isServer); // initialize the store
    return { helloMessage: store.helloMessage, isServer }; // pass the initial values down as props
}

constructor (props) {
    super(props); // use initial server values to initialize the client props
    this.store = initBaseStore(props.isServer, props.helloMessage);
} 

I haven't tested this, you can find this approach here

Thanks @supra28, it seems a good idea

Was this page helpful?
0 / 5 - 0 ratings

Related issues

formula349 picture formula349  路  3Comments

jesselee34 picture jesselee34  路  3Comments

pie6k picture pie6k  路  3Comments

rauchg picture rauchg  路  3Comments

swrdfish picture swrdfish  路  3Comments