3

I'm developing with react-router-dom. Now, I'm creating a page where users can enter information in a form. What I want to do is prevent the user from losing the information they enter if they accidentally return to the previous page.

I first found a way to stop the browser back in the article below. It seems that the moment you return to the previous page, you immediately return to the original page, effectively preventing you from returning to the previous page.

React.useEffect (() => {
    return () => {
            props.history.goForward ();
        }
    }, []);

React Router Dom v4 handle browser back button

However, in this case, the previous page will be returned once, so all the current page information (state) will be reset. Is there a solution to prevent the state from resetting? Or is there a smarter way to solve this?

Below, I have prepared an image for explanation.

enter image description here

karutt
  • 359
  • 1
  • 11

1 Answers1

3

You have several ways to approach your answer, but all of them have 1 concept, and that is Higher-order-component, so in this case, you have to have a top-level component (Higher than react-router), so when the location has changed, you don't lose the information in the state. in another word, you have to have a general state.

So how you can reach this goal? you have several ways and I'm here to help you use them.

  1. redux - https://redux.js.org/.
  2. context - https://reactjs.org/docs/context.html.
  3. react state - https://reactjs.org/docs/higher-order-components.html.
  4. localStorage or sessionStorage - https://www.robinwieruch.de/local-storage-react.
  5. ...

these are just some examples of what you can do to prevent losing state when the browser location has changed.

Mahdi
  • 1,355
  • 1
  • 12
  • 28