Skip to content Skip to sidebar Skip to footer

Correct Way To Fetch Data When Switching Route On Same Level In React-router?

What is the correct way to fetch data when switching route on same level? Because, according to this, switching route on same level will only call componentWillReceiveProps and com

Solution 1:

From the React Router docs:

componentDidMount () {
  // fetch data initially in scenario 2 from above
  this.fetchInvoice()
},

componentDidUpdate (prevProps) {
  // respond to parameter change in scenario 3
  let oldId = prevProps.params.invoiceId
  let newId = this.props.params.invoiceId
  if (newId !== oldId)
    this.fetchInvoice()
}, 

When route changes this.props.params.userId will update, which is caught in componentDidUpdate, and fires off a fetch. Of course this fetch will likely update state or props firing another re-render to show the fetched data.


Post a Comment for "Correct Way To Fetch Data When Switching Route On Same Level In React-router?"