Christopher
Christopher

Reputation: 15

reactjs react router picking up changes in the url

I know you can access params id in a url using this.props.match.params. My question is how do you pick up changes the user may have manipulated in the url? Ex: orginal url passed from router in props http://localhost:3000/user/3456653/newPage

The user fills out the page and messes with the url params id Ex: http://localhost:3000/user/888888/newPage

Is there a way I can check if the params are the same before making my api call to store the data? I am using "react-router-dom": "4.2.2"

Upvotes: 0

Views: 61

Answers (1)

Tholle
Tholle

Reputation: 112787

You can compare your parameters in the componentDidUpdate hook of the component given to your Route to find out when it changed.

Example (CodeSandbox)

class MyComponent extends Component {
  componentDidUpdate(prevProps) {
    const prevPathParameter = prevProps.match.params.pathParameter;
    const newPathParameter = this.props.match.params.pathParameter;

    if (prevPathParameter !== newPathParameter) {
      console.log("pathParameter changed!");
    }
  }

  render() {
    return <h1> {this.props.match.params.pathParameter}</h1>;
  }
}

function App() {
  return (
    <Router>
      <div>
        <Link to="/home">Home</Link>
        <Link to="/about">About</Link>
        <Route path="/:pathParameter" component={MyComponent} />
      </div>
    </Router>
  );
}

Upvotes: 1

Related Questions