Error trying to access a property of an object in a React component

3

I have a problem accessing information from an array that has an object inside, using React.

This is the function that brings my json and changes the state of the application, it creates a times.name, times.players and times.foto, in case this will turn an array of objects

getTimes () {
    ajax().get('./src/json/times.json')
  .then(result => {
            this.setState({
                times: result.map((time) => ({
                    nome: time.time,
                    players: time.player,
                    fotos: time.foto
                }))
            })
        })
}

Here I move it to my app-content

render() {
    return <AppContent 
        times={this.state.times}
    />
}

In it, I render my component

<TimeCasa times= {times} />

So far so good, but there in my component

const TimeCasa = ({times}) => {

let pos = times[0]
console.log(pos)
return (
<div className='wrapper-casa'>
    <h1 className="time">{pos.nome}</h1>

times [0] finds the object normally and I assign it to the variable pos, within that variable I called the pos.name and it of the error saying that it is not possible to access name of undefined, being pos is not undefined, it is an object that contains the key name. Does anyone know what it can be?

    
asked by anonymous 19.11.2018 / 23:00

1 answer

1

As shown in the question, the code seems to work normally when tested in a sandbox .

This may be occurring due to timing problems, where the rendering of component TimeCasa is being called before the times state is populated.

This is a fairly common problem when dealing with asynchronous methods or not having an immediate response.

A good way to fix this is by using the Short Circuit Evaluation , or Conditional Rendering .

You could simply check if the value of pos (assuming it has a reference of the first value of the array times ) is a truthy value:

<h1 className="time">{pos && pos.nome}</h1>

If you do not understand very well, I recommend reading this answer and the link I left above about conditional rendering.

How could I do to hold render until ajax is finished?

Before the render is called, the componentWillMount method is called, you can do the operations inside it, but even then it is not certain that they will be finished before the render is called, and it is not very recommended that the use here because.

A form that would guarantee would return nothing in render if the value of times is not yet filled, but I also do not recommend that you do this, maybe show a loading be better.

    
20.11.2018 / 02:39