2

Is there a way to check the next location via React Router? I am not interested in using Prompt solution. My goal is to set some condition on component unmount like:

useEffect(() => {
  return () => {
    if(nextRoute !== '/something') {
      resetData();
    }
  };
}, []);

Is there a way to have a knowledge what is the nextRoute?

jake-ferguson
  • 315
  • 3
  • 11
  • 32
  • Why not run `resetData()` from within the component that handles `'/something'` route within a useEffect()? – Oliver Heward Nov 16 '21 at 11:54
  • Hey, good question, My bad, I've just edited the question. I want to resetData always but not for this one particular route. – jake-ferguson Nov 16 '21 at 11:57
  • You should be able to reach for the location object within props and do something like the below `const something = ({location}) => { useEffect(() => { if(location.pathname !== '/something') resetData(); }, [location]) return ( // some jsx) }` – Oliver Heward Nov 16 '21 at 12:01
  • Yeah but in such case I will reach the CURRENT location, my point is to get the NEXT location (destination) that the user is redirecting to – jake-ferguson Nov 16 '21 at 12:03
  • Hmm, I'd probably say that you would need to run a callback from the onClick event that occurs on route change, or run a function to do a similar method. That is of course if the user is interacting with a link that will push them to another route, just that useEffect is a lifecycle adaption for component mounting/unmounting/remounting. How does the user reach the next page, from a Route click? – Oliver Heward Nov 16 '21 at 12:07
  • https://stackoverflow.com/questions/41911309/how-to-listen-to-route-changes-in-react-router-v4 – Oliver Heward Nov 16 '21 at 12:11

0 Answers0