Hadi Ranjbar
Hadi Ranjbar

Reputation: 1802

URL params have not updated yet when we listent to history in react router

I have a url listener in my component like this:

  this.urlListener = this.props.history.listen(location => {

      console.log(this.props.match.params.cityname);

    });

The problem is that when I update the URL, I want to access to new parameters. But, this.props.match.params still contains params with the old values.

My route URL is /a/:cityname

In console.log() I see past cityname, not the new one.

Upvotes: 1

Views: 212

Answers (1)

Hadi Ranjbar
Hadi Ranjbar

Reputation: 1802

I found that react-router-dom matches the url and gives you parsed url based on params and search queries:

import { withRouter, matchPath } from "react-router-dom";

   let urlmatch = matchPath(location.pathname, {
        path: this.props.match.path
      });

So urlmatch contains new params.

BingO!

Upvotes: 2

Related Questions