C
C
cajo2017-04-01 00:14:23
JavaScript
cajo, 2017-04-01 00:14:23

Why does componentDidUpdate cause an infinite loop?

I have a Link to the page, on this page I call in componentDidMount an action that takes data from the server, when I go to this page the data is not taken but a 403 error pops up, after refreshing the page everything is fine, to bypass this I did

componentDidMount() {
        this.props.loadData();
    }

    componentDidUpdate(prevProps) {
        if (prevProps.data !== this.props.data) {
            this.props.loadData();
        }
    }

But now it's an endless loop

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Damir Makhmutov, 2017-04-01
@cajo

If I understood you correctly, then prevProps.data and this.props.data are objects.
I can assume each time these are references to different objects, and you need to compare specific properties of the object.
You can use lodash and do this:

componentDidUpdate(prevProps) {
    if (!_.isEqual(prevProps.data, this.props.data)) {
        this.props.loadData();
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question