mr.abdo
mr.abdo

Reputation: 485

How can I detect refresh page and routes change in react?

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?

Upvotes: 1

Views: 1263

Answers (2)

cubefox
cubefox

Reputation: 1301

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)
    }
  }

Upvotes: 0

Diamond
Diamond

Reputation: 3428

You can call componentsHandler function in componentDidMount.

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

Upvotes: 2

Related Questions