Queue calls and wait for state updates in React.js

I have a function that I run in a loop forEachin a child component, the function should filter the data and update the state with the result. The problem is that when I repeat the function with a loop, it starts everything at the same time and inside this state the state will not be updated correctly with data. The question is how best to implement it, maybe there is a way with Promise or async / await, or maybe something simpler that will do the job. As necessary, to queue and wait for the status to be updated.

Simplified code is here a
child component

this.props.data.forEach((item, i) => {
    this.props.update(item);
});

parent component

function update(data) {
    let filtered = this.state.data.filter(item => item.uid !== data.uid);
    this.setState({data: filtered});
}
+4
2

, - :

update = () => {
    let filtered = this.state.data.filter(x => this.props.data.every(y => x.uid !== y.uid))
    this.setState({
        data: filtered
    })
}
+2

?

:

this.props.update(this.props.data); // pass the entire array

:

function update(data) {
    let filtered = data.map(d=> {
        return this.state.data.filter(item => item.uid !== d.uid);
    }
    this.setState({data: filtered});
}
+2

Source: https://habr.com/ru/post/1684592/


All Articles