-1

I want to update the state of my application when a router component is rendered. For example, if I go home "/" I will render homepage, but I want to trigger a state change so that other components like my footer and header are aware we are on the home page vs internal page. Currently, I am parsing the url manually when site is loaded to detect this, however, as the site grows this is unfeasible. I have also seen onEnter as a solution, however, this is not available for reach router.

 <Router basepath={process.env.PUBLIC_URL} className="app" >
          <LandingPageBody path="/" default/>
           //update redux state to show we are on homepage
 </Router>
Saad Khan
  • 49
  • 4

2 Answers2

1

You can use componentDidMount in LandingPageBody component. It is a react lifecycle method it will be triggered when component will mount. You can update state from inside of this method.

0

If you are using functional components, make use of useEffect function with dependency on props.match.location. Check for condition in that and dispatch action if the condition is true.

(React.useEffect(() => { if(props.match.location === 'desired path') dispatch(action) }, [props.match.location]))

This way when ever your route component loads, it will check for route on every route change and let your redux store know about the current path.

For Stateful component, you can do the same in componentDidUpdate lifecycle.

Sumair
  • 103
  • 1
  • 2
  • 8
  • Would I need to do this for every route? For instance, if I load an internal page I want my redux store to know that I am now in that page – Saad Khan Feb 17 '21 at 03:13
  • No, @SaadKhan, Just make a container and add this effect on top level and you're good to go. p.s: Render other components as children of this container. – Sumair Feb 18 '21 at 06:35