0
votes

Probably it's a newbie question... I get a json response with an object from a fetch() running into a function on componentDidMount(). The result is saved into a state

    data: 
    {
    id: 1,
    name: 'joseph',
    tickets: 
              [
              {id: 334, descripton: 'example1'},
              {id: 768, descripton: 'example2'},
              ],
    }

I need to list this array "tickets" in render ().

componentDidMount(){
  this.getFetch(...);
}

showTickets(WTickets){
  console.log(WTickets);
  WTickets.map((item)=>{
    return (item.id)
  })
}

render(){
  return(
    <View>
      {this.showTickets(this.state.data.tickets)}
    </View>
  )
}

But the "first return" is "undefined", generating error and then the state changes to the correct result. The fetch is running with async await, but still show the "undefined" first.

The console.log show 2 results: one "undefined" and another with the result.

Any good soul to help me, please?

1
showTickets will return undefined because you don't actually return anything... doesn't matter if WTickets is the expected array. Maybe it should be: return WTickets ? WTickets.map(...) : [];Robert Berglund

1 Answers

1
votes

It's because at the start this.state.data.tickets is undefined and you are calling it in the render function which is not gonna wait until this.getFetch() finishes. So.. you can do a conditional rendering to check if this.state.data.tickets exist in rendering

replace {this.showTickets(this.state.data.tickets)}

with {this.state.data!==undefined? this.showTickets(this.state.data.tickets) : null}

What we are doing here is first checking if this.state.data.tickets is not undefined. While it is undefined (at the start) we return null, when it stops being undefined we call this.showTickets.

You can even initialize this.state.data as an empty array, and you can delete the part when we check if it's undefined since an empty array will return false

constructor() {
    super();
    this.state = {
      data: []
    };
  }
....
....
//in render function
{this.state.data? this.showTickets(this.state.data.tickets) : null}
...