1

I have to call an specific function (componentsHandler) every time that the route changes or the page is refreshed.

This function is responsible to deal with some components states

componentsHandler(menuItem, event) {
    switch (menuItem) {
      case '/':
        this.headerTitleHandler('Search')
        this.searchBarHandler(true)
        break
      case '/dashboard':
        this.headerTitleHandler('Dashboard')
        break
      case '/administration':
        this.headerTitleHandler('Admin')
        this.searchBarHandler(false)
        this.searchBarInfoHandler(false)
        break
      default:          
    }
  }

So, when the route changes I call componentsHandler function using componentDidUpdate:

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      this.componentsHandler(this.props.location.pathname)
    }
  }

The problem is that when I refresh the page, componentDidUpdate doesn't detect it and the componentsHandler function is not called.

How can I deal with it?

4
  • 1
    does it work when you click manually ? Commented Jun 28, 2019 at 12:32
  • @NikhilPatil yes. It doesnt works if I refresh the page Commented Jun 28, 2019 at 12:33
  • 1
    are you using used react-router ? for routing Commented Jun 28, 2019 at 12:36
  • yep..sorry for didnt write it Commented Jun 28, 2019 at 12:37

2 Answers 2

2

You can call componentsHandler function in componentDidMount.

  componentDidMount() {
     this.componentsHandler(this.props.location.pathname);
  }
Sign up to request clarification or add additional context in comments.

3 Comments

componentDidMount() called only once ! I think it won't work.
@NikhilPatil When we refresh or route is changed by users, the component is destroyed and created again when you visit again. That means componentDidMount should be called every time when you visit by route or refresh.
yes you are right whenever component is rendered componenetDidMount() get's called. My Bad!
0

On refresh your app is rendered from scratch. You need a handler for componentDidMount and componentDidUpdate (or just useEffect if you use hooks)

  componentDidMount() {
      this.componentsHandler(this.props.location.pathname)
  }


  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      this.componentsHandler(this.props.location.pathname)
    }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.