Prevent state from being lost when using history.push() - React-router-dom - Reactjs

Asked

Viewed 28 times

1

I have a component that calls the API and stores the return in the state to display to the user. However, when I use the history.push() to navigate to another application page and then use the history.goBack() the state of the previously loaded component is lost and a new API request is made. How do I make sure that this data is not lost?

I’m using the react-router-dom to manage my routes.

  • you probably would have to do the storage of the data to be able to restore the state when the user returns to the page, in which case there are several ways to do it, you can implement a Storage scheme using localStorage or sessionStorage, but in case you need a more elaborate cache strategy I suggest you take a look at react-query

  • Look without seeing the code is kind of difficult, but I would recommend using a context and within it put the pages that were navigated in an Array, and so adding to each page change, and when you want to turn a page back take the penultimate element of the Array

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.