Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks - remove from react-router location state when we refresh page

When I am entering one page of the app I pass data through location state using react-router. Then I access it via location.state.myDataObject. When I refresh the page it is still there, while I would like it to be empty. Here's what I've try to use:

  const resetLocation = () => {
    history.replace({
      ...location,
      state: undefined,
    });
  };

  useEffect(() => {
    window.addEventListener('onbeforeunload', resetLocation);
  }, []);

Or adding it to unmount action within useEffect but I guess it is not called when refreshing the page:

  useEffect(() => {
    return function cleanLocationState() {
      history.replace({
        ...this.props.location,
        state: undefined,
      });
    };
  }, []);
like image 475
heisenberg7584 Avatar asked Oct 07 '20 10:10

heisenberg7584


People also ask

How do you prevent state change in React after page refresh?

To maintain state after a page refresh in React, we can save the state in session storage. const Comp = () => { const [count, setCount] = useState(1); useEffect(() => { setCount(JSON.

How do you delete a location on state React router?

In React Router v6 you can do: const location = useLocation(); const navigate = useNavigate(); const state = location. state; // Do some stuff with the state // ... // Clear the state after navigate(location. pathname, { replace: true });

Does React router reset state?

React-router resets all states of App component when I change route.

Does React router refresh the page?

react-router-dom allows us to navigate through different pages on our app with/without refreshing the entire component. By default, BrowserRouter in react-router-dom will not refresh the entire page.


1 Answers

I think this is the desired behavior of react router. If you want to reset the state then you need to do something like

import React, { useEffect, useCallback } from "react";
import { useLocation, useHistory } from "react-router-dom";

function Home() {
  const location = useLocation();
  const history = useHistory();
  const replaceHistory = useCallback(() => {
    history.replace({ ...location, state: undefined });
  }, [history]);

  useEffect(() => {
    window.addEventListener("beforeunload", () => replaceHistory);
    return () => {
      window.removeEventListener("beforeunload", replaceHistory);
    };
  }, []);

  return (
    <div>
      <h2>Home</h2>
    </div>
  );
}

export default Home;

Working example

like image 80
Diego Segura Avatar answered Sep 23 '22 10:09

Diego Segura