KamSami
KamSami

Reputation: 407

How to have a callback function after setting the state for each individual loop in a forEach loop?

trying to callback a function after each individual loop after setting the state. but the callback will execute twice with the most recent state rather then both states.

onAddClick = () => {
    this.state.tempAddList.forEach((id) => {
        console.log("add", id);
        this.setState({modInfo: {...this.state.modInfo, modId: id}},()=>this.addModifier());
    });

};
addModifier = () => {
    console.log(this.state.modInfo);
    EdmApi.insertModifier(this.state.modInfo)
        .then(res => console.log(res))
        .catch(err => console.log(err));

};

Upvotes: 0

Views: 50

Answers (1)

Estus Flask
Estus Flask

Reputation: 223258

this.state shouldn't be used together with setState because state updates are asynchronous. This may result in race condition, which is the problem here.

This is what updater function is for:

this.state.tempAddList.forEach((id) => {
    this.setState(
      state => ({modInfo: {...state.modInfo, modId: id}}),
      ()=>this.addModifier())
    ;
});

Upvotes: 1

Related Questions