EmFor
EmFor

Reputation: 93

How to maintain component state after page rerender/change?

I have a counter made using context API and I need it to maintain the current state after the page is changed. Is there any way to keep the Counter value on page change like in session storage or something? I'm using react router to change the pages.

export const CounterContext = React.createContext()



function App() {

  const [Counter, setCounter] = useState(0)
  useEffect(() => {
    setCounter(JSON.parse(window.localStorage.getItem('count')));
  }, []);

  useEffect(() => {
    window.localStorage.setItem('count', Counter);
  }, [Counter]);
  
  function ChangeCounter() {
    setCounter(Counter+1);
  }
  console.log(Counter);

  return (
    <CounterContext.Provider value={{Counter, ChangeCounter}}>
    <Router>
    <div className="App">
      <header className="App-header">
        <Navbar />
      </header>
      <div className="Content">
        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/Products">
            <Products />
          </Route>
          <Route path="/Contact">
            <Contact />
          </Route>        
        
        </Switch>
      </div>
      
      <footer>
        <Footer />
      </footer>
    </div>
    </Router>
    </CounterContext.Provider>
  );
}

Edit:
I made it using local storage but I'm not really sure is that what I wanted. Now even on browser restart the counter stay on the same updated value but I want it to refresh. Is there a way to do that now?

Upvotes: 0

Views: 1239

Answers (2)

Ayush Singh
Ayush Singh

Reputation: 126

You can use cookies for this functionality. You can prefer universal-cookie to manipulate cookies in react

npm install universal-cookie

Upvotes: 1

EmFor
EmFor

Reputation: 93

Ok I made it. Thanks a lot everyone! I used the sessionStorage to stor the data only during the session. It looks like this:

export const CounterContext = React.createContext()



function App() {

  const [Counter, setCounter] = useState(0)
  useEffect(() => {
    setCounter(JSON.parse(window.sessionStorage.getItem('count')));
  }, []);

  useEffect(() => {
    window.sessionStorage.setItem('count', Counter);
  }, [Counter]);

  function ChangeCounter() {
    setCounter(Counter+1);
  }
  console.log(Counter);
//and the rest  of the code...
}

Upvotes: 1

Related Questions