1

I am trying to iterate through data and displaying it in my react app. My code works until I store the results in the the components state. Somehow (I marked it insight the code as 'HERE IT DOESNT WORK ANYMORE' as its hard to explain. I have rewrote my actual code because I didn't want to post hundreds of lines of code here :) and also exchanged the data (which I am actually receiving making an http request) with an object (which I only resized) - so please don't pay attention if some parts of the code look weird/too much as my actual code is much bigger. I also added a codepen link here-where you can't see anything (because its not working) but I included console.logs so you can see what I mean. Thank you very much for any help!!

https://codepen.io/helloocoding/pen/vWVLmp?editors=1010

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: PricedItineraries,
            result: []
        }
        this.handleInput = this.handleInput.bind(this);
        this.showSearchResults = this.showSearchResults.bind(this);
    }

    showSearchResults(obj) {
        console.log("func", this.state.data)
        var allTrips = [];
        var TotalPriceTemp = [];

        for (var i = 0; i < obj.length; i++) {
            var o = obj[i];
            allTrips.push(o.AirItinerary.OriginDestinationOptions.OriginDestinationOption)

            var totalFair = o.AirItineraryPricingInfo.PTC_FareBreakdowns.PTC_FareBreakdown.PassengerFare.TotalFare;
            TotalPriceTemp.push(totalFair.Amount);
        }

        for (var i = 0; i < allTrips.length; i++) {
            var MarketingAirlineTo = [];
            var MarketingAirlineBack = [];
            var TotalPrice = 0;
            var oneWay = allTrips[i][0];
            var returnTrip = allTrips[i][1];

            oneWay.FlightSegment.forEach(function (flightTo) {
                MarketingAirlineTo.push(flightTo.MarketingAirline.Code);
            })

            returnTrip.FlightSegment.forEach(function (flightTo) {
                MarketingAirlineBack.push(flightTo.MarketingAirline.Code)
            })

            TotalPriceTemp.forEach(function (item) {
                TotalPrice += item;
            })
            var tempFlightsObject = [];

            tempFlightsObject.push({
                marketingAirlineTo: MarketingAirlineTo,
                marketingAirlineBack: MarketingAirlineBack,
                TotalPrice: TotalPriceTemp[i]
            })
            console.log("tempFlightsObject", tempFlightsObject)
            this.setState({
                result: tempFlightsObject
            })
            console.log("result", this.state.result)
            //HERE IT DOESNT WORK ANYMORE: TEMPFLIGHTOBJECT shows correct data, but result doesn't
        }
    }

    handleInput() {
        console.log("handeInput func", this.state.data)
        this.showSearchResults(this.state.data);
        console.log("handeInput func -result", this.state.result)
    }

    render() {
        const flights = this.state.result.map((item, i) => {
            return (
                <div>
                    <div key={i}><p> {item.marketingAirlineTo} </p></div>
                </div>
            )
        })

        return (
            <div>
                <button onClick={this.handleInput}>click me</button>
                <div> {flights}</div>
            </div>
        )
    }
}


React.render(<App />, document.getElementById('app'));

3 Answers 3

3

setState may be executed asynchronously by react to batch updates and optimize performance.


You can provide a callback to setState, which will be called once the update has actually been completed:

this.setState({
    result: tempFlightsObject
}, function () { console.log("result", this.state.result) })
Sign up to request clarification or add additional context in comments.

Comments

2

setState is an asynchronous function. React batches updates together for performance reasons. See https://reactjs.org/docs/react-component.html#setstate for more information.

Your component should re-render, but you may not be able to log the state immediately after you set it. If you want, you can add a callback as the second argument to setState, which takes state as its first and only argument.

Comments

1

setState may be batched.

this.setState({ result: tempFlightsObject }, () => { console.log("result", this.state.result) })

will work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.