简体   繁体   中英

Next.js - _app.js state is lost on page refresh / SSR

Not sure if this is a feature or a side-effect of rendering server side but any state stored in the exposed _app.js page is lost whenever I either refresh page or visit page directly from url input. Next.js proclaim the _app.js page is for "Keeping state when navigating pages", so this should work.

All state is kept when routing client side with the <Link> component.

I'm trying to store non-sensitive data without using cookie/session/local storage.

Can anyone validate if this is the best approach or should I just be using one of these techniques?

Happy to post code if necessary.

Next.js apps uses SRR that means your application is universal. When you are navigating through pages without refresh this occurs in client-side, when you refresh your page this occurs in the server-side. You can use cookies to persist the data what you need because you can access the cookies both client and server, so when you refresh the page you can check if the cookie exist and do some stuff according to this.

I was in the same situation as you. So I wrote a boilerplate example of this. Go visit the example and the code to implement this in your app. https://github.com/fazlulkarimweb/with-next-redux-wrapper-redux-persist

反例

There are no official examples from the Next community for this for now. I think people who are trying to find a solution will be helped by the boilerplate.

If your application is large enough, then use redux for state management. For getting back states on page refresh, you can use redux-persist which can be integrated with next-redux-wrapper. Basically redux-persist save your redux store in local storage. You can refer these links:

https://github.com/rt2zz/redux-persist https://github.com/kirill-konshin/next-redux-wrapper

When you refresh the page, _app.js kicks in, and its code reexecuted. Every state you set inside _app.is only for the current browser session. If you want to persist the state, you have to use cookies or use Localstorage

But if you are re-routed to a new page, your app does not get rerender so _app.js code does not get executed. That is why you might see a warning by next.js if you are navigating with <a> element. "Do not use an <a> element to navigate to / . Use <Link /> ". That is why next.js proclaims:"Keeping state when navigating pages"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM