Search code examples
javascriptreactjsreact-routerstaterouterlink

How to update state that is passed through react router link


So I am using react-router, and after I send some state with the Link from page1 to page2

<Link
  to={{
    pathname: `/dashboard/edit/${resort.id}`,
    state: { resort: resort },
  }}
  style={{ textDecoration: 'none', color: 'black' }}
>
  <i
    className="fas fa-edit db-icon"
    style={{ background: 'rgb(12, 177, 12)', color: 'black' }}
  ></i>
</Link>;

When I enter page2, how do I update this state, I've tried using this.setState, but that doesn't work, I've tried destructuring the state sent over like below but that didn't work either

constructor() {
  super();
  this.state = {
    title,
    price,
    desc,
    img,
    smoking,
    guests,
    featured,
  } = this.props.location.state.resort;        
}

Any suggestions?


Solution

  • NEVER mutate this.state directly

    Try like this:

    constructor() {
      super();
      this.state = { resort: {} };      
    }
    
    componentDidMount = () => {
      this.setState({resort: this.props.location.state.resort});
    }