How to fetch data when a React component prop changes?

Constructor is not a right place to make API calls.

You need to use lifecycle events:

  • componentDidMount to run the initial fetch.
  • componentDidUpdate to make the subsequent calls.

Make sure to compare the props with the previous props in componentDidUpdate to avoid fetching if the specific prop you care about hasn’t changed.

class TranslationDetail extends Component {    
   componentDidMount() {
     this.fetchTrans();
   }

   componentDidUpdate(prevProps) {
     if (prevProps.params.id !== this.props.params.id) {
       this.fetchTrans();
     }
   }

   fetchTrans() {
     this.props.fetchTrans(this.props.params.id);
   }
}

Leave a Comment