3
I’m having 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.photo, in case this will turn into 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 pass it to my app-content
render() {
return <AppContent
times={this.state.times}
/>
}
In it, I re-dress 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 this variable I called pos.name and it from the error saying that it is not possible to access Undefined name, pos being not Undefined, it is an object that contains the key name. Does anyone know what it can be?
What is the return of
console.log(pos)
?– Francisco
Smooth running here: https://codesandbox.io/s/p7yvo599qm
– Francisco
The return of the console.log(pos) is: {name: "Time A", players: Array(5), photos: Array(5)}
– Rodolpho
Dude, tell you what, put one on
{pos && pos.nome}
inside H1, see if it goes– Francisco
It worked!! Can you explain why? Just to explain something to you, if I tried to put only {pos} inside H1, it gave error because I was trying to put an object like Child, until then blz, it’s supposed to be wrong, but if I didn’t close the page, back in the code and put in the.name and let the hot Load update, it worked, when I gave F5 stop again... doing it your way worked!
– Rodolpho
The surrender of the Timecasa was being called before the ajax ended, one should take this kind of care.
– Francisco
I understood perfectly, how could I hold the surrender until the ajax is finished? and just to learn why with {pos && pos.name} it waits for ajax to end? I don’t understand the difference
– Rodolpho
I wrote a more complete answer, in case I helped solve your problem, please mark it as correct. =)
– Francisco
Thank you very much, you helped me a lot!
– Rodolpho