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'));