Home > Enterprise >  Prevent data to disappear when switching page
Prevent data to disappear when switching page

Time:04-04

So, I'm making this app where I need to fetch 3 different sets of data, "yesterday, today, tomorrow" and show them on different pages. The problem is that when I switch pages and go back the data is gone and I need to fetch it again and that is a waste of network recourse, I have searched a bit about this, and looks that the best way to save data and prevent it to disappear its to use Redux or localStorage. I'm using react Router. Any recommendation?

CodePudding user response:

I know a lot of people may disagree, however for educational purposes if you want to learn how to use Redux, it may be worth checking out Redux-Toolkit - https://redux-toolkit.js.org/

RTK has a few cool features whilst also allowing you to reduce boilerplate that you find inside redux.. RTK also supports SWR - Stale With Revalidation, essentially caching values, so you don't need to continue to fetch the data from the backend.

Give it a look, worth your while even just for educational purposes.

CodePudding user response:

Redux is a great option, however, there is no need to use it in simple projects. The localStorage option is a very good one.

for example:

Read data:

const data = localStorage.getItem("fileName");
if (data) {
  setData(JSON.parse(data)); // or do anything you like with this data
}

Save data:

localStorage.setItem("fileName", JSON.stringify(dataToSave));

simple as it is...

CodePudding user response:

While both Redux and LocalStorage would work I would personally opt for react-query. The result of the requests get cached avoiding unnecessary calls

https://react-query.tanstack.com/overview

  • Related