Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React get new data in componentDidUpdate

I have a component which receives a list of news from two or three APIs. the first time the component renders, the apis are called and data is rendered in componentDidMount something like this:

componentDidMount() {
        this.state.platforms.forEach((platform, i) => {
            let objToSend = {
                phrase: this.props.searchParams.phrase,
                // this is the main place when input data changes
                ...this.props.searchParams.general_params,
                ...this.props.searchParams.platforms[i].api_params,
                stringPath: platform,
                apiPath: this.props.searchParams.platforms[i].apiPath,
            }
            this.props.loadData(objToSend)
            // this is the api call using redux which sends data as props to this component
 }

new when the phrase change, I want this component to re-render and re-run the componentDidMount, but it's not working because componentDidMount will run once. So I used componentDidUpdate, but as there are a number of calls so the api is being updated continuesly.

How can I make the component re-render and re-run componentDidMount every time I change the phrase

like image 295
Amir Shahbabaie Avatar asked Feb 06 '26 03:02

Amir Shahbabaie


1 Answers

You can use componentDidUpdate arguments (previousProps, previousState) to check whether some new changes happened.

Example

componentDidUpdate(previousProps, previousState) {
    if (previousProps.phrase !== this.props.phrase) {
        //Do whatever needs to happen!
    }
}

I stopped the infinite loop for my situation this way.

like image 81
Alex Jolig Avatar answered Feb 07 '26 19:02

Alex Jolig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!