Categories
React Answers

How to Fetch Data When a React Component Prop Changes?

Spread the love

Sometimes, we want to fetch data when a React component’s prop changes value.

In this article, we’ll look at how to fetch data when a React component’s prop changes value..

How to Fetch Data When a React Component Prop Changes

To fetch data when a React component changes, we can add the componentDidUpdate method to our class component.

It takes a parameter for the previous prop value.

We can use that to compare with the current prop value to determine if we want to fetch data or not.

If they’re different, then we do the fetching.

For instance, we can write:

class App extends Component {
  componentDidMount() {
    this.fetchData();
  }

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

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

We have the componentDidUpdate method that has the prevProps parameter.

We compare the id from prevProps to the id in the current prop to determine if we want to call fetchData .

Conclusion

To fetch data when a React component changes, we can add the componentDidUpdate method to our class component.

It takes a parameter for the previous prop value.

We can use that to compare with the current prop value to determine if we want to fetch data or not.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *