Home > Enterprise >  How can I run code on a route change from certain pages using react-router 5
How can I run code on a route change from certain pages using react-router 5

Time:01-08

I've found lots of examples on v4 with the onLeave function. it seems this was discontinued after v4 however.

I've seen some <Prompt> examples but dont think thats what i'm looking for. if you have a case that will work i am open to it.

My Scenario: React v16 app where i have multiple tables. I have a section in the store (global state) where i retain certain ui preferences. the tables paginate and reuse some of the same state info for pagination, sort, etc.

user story - user selects page 4, then navigates to another table, is still on page 4 (pagination is read from the store). I simple want to purge the values from state (im using redux so i will call an action to do this) but how can i trigger that, for example, on only a few routes in my app. this way i can reset it on leave and its ready by the time the user gets to the next table?

//edit for comment 1, basic example
const routes = [
  {
    path: "/one-thing",
    component: OneThing,
  },
  {
    path: "/two-thing",
    component: TwoThing,
  }, 
...

this is a huge app, but this might clarify. How can i run code, when i leave the path /one-thing?

we used to be able to do this in v4

  {
    path: "/two-thing",
    component: TwoThing,
    onLeave: doAThing,
  }, 

CodePudding user response:

Sounds like you could either listen for changes to the current location via the history object in a parent component.

history.listen

import { useHistory } from 'react-router-dom';
import { useEffect } from "react";

...

const history = useHistory();

useEffect(() => {
  const unlisten = history.listen((location, action) => {
    console.log('Route changed', { location, action });
    // Apply route change logic, i.e. dispatch to store
  });
  return unlisten;
}, []);

Or use unmounting useEffect cleanup function in the component with table.

import { useEffect } from "react";

...

useEffect(() => {
  return() => {
    // component unmounting (maybe from route change)
    // Apply route change logic, i.e. dispatch to store
  };
}, []);
  •  Tags:  
  • Related