Search code examples
reactjscomputed-fieldsetstate

React change state in array (for loop)


I have a State with flights, and I have a slider to change the max price to change visibility of the flight elements.

maxpriceFilter() {

    var flightOffer = this.state.flightOffer;
    var sliderPrice = this.state.sliderPrice;

    for (var i = 0; i < flightOffer.length; i++) {
        if( flightOffer[i].price > sliderPrice) {   

            this.setState(
                {[flightOffer[i].hiddenprice] : true}
            );
        };
    }

This code is adding a undefined field with status true in the root of the state though.. I cant find any best practice on this, other then using computed fields. But I cant get the computed field working either..

Could someone please help me out here?


Solution

  • You don't want to do a setState call in a loop, that will have the react component render multiple times. Build a new state object and call the setState once. You also don't want to filter it out by an if statement, but set previous values to hidden:

    maxpriceFilter() {
    
        var flightOffer = this.state.flightOffer;
        var sliderPrice = this.state.sliderPrice;
        var newState = {};
    
        for (var i = 0; i < flightOffer.length; i++) {
            newState[flightOffer[i].hiddenprice] = flightOffer[i].price > sliderPrice;
        }
    
        this.setState(newState);
    
        // ...
    }
    

    If you're still having issues, it could be that the hiddenprice property isn't what you expect? Might need to post your render() function as well.