2

While setting state , Even-though length of array is 9, Its displaying only first value. I'm not sure where its going wrong.

_GoTown = () => {
    if (this.state.stTownRawData == '') {
        alert(i18n.t('plsseltown'));
    }
    else {
        this.setState({ stAtmList: [] });
        var rartown = this.state.stTownRawData;
        for (i = 0; i < rartown.length; i++) {
            console.log(i);
            this.setState({ stAtmList: this.state.stAtmList.concat({ key: i, town: i18n.t('town') + rartown[i].town, address: i18n.t('add') + rartown[i].addressLine1, lat: rartown[i].latitude, long: rartown[i].longitude, icon: require('../../resources/toolbar/atm.png') }) });
        }
        console.log(rartown);
    }
}

Console.log(i) returns values from 0 to 8. I'm not sure why setState is populating stAtmList with only first value.

Kartiikeya
  • 2,358
  • 7
  • 33
  • 68

1 Answers1

1

setState is async so even if you set the value as [] in first line, it's not necessary that in next line you will get the updated value.


Issue is, You are updating the state value in loop, so there is no guarantee that in next iteration state will have the updated value. Use a variable and push all the values inside that, and update the state at the end means when for loop ends.

You need to write it like this:

_GoTown = () => {
    if (this.state.stTownRawData == '') {
        alert(i18n.t('plsseltown'));
    }
    else {
        let stAtmList = []
        let rartown = this.state.stTownRawData;
        for (let i = 0; i < rartown.length; i++) {
            stAtmList.push({ key: i, town: i18n.t('town') + rartown[i].town, address: i18n.t('add') + rartown[i].addressLine1, lat: rartown[i].latitude, long: rartown[i].longitude, icon: require('../../resources/toolbar/atm.png') }) });
        }
        this.setState({ stAtmList });
    }
}

Check this answer for more details:

Why calling setState method doesn't mutate the state immediately?

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142