Reputation: 59
I'm trying to access some data from an API but when I do I get Cannot read property '5' of null
import React from "react";
function Card(props) {
console.log(props.data[5].mission_name); //why is it that this doesn't work in my machine?
console.log(props.data); //this works with my machine
return (
<div>
<h1>test</h1>
</div>
);
}
export default Card;
I initially set the data that I'm passing as null and then I update it once the data from the API loads so I'm thinking that might be part of the problem but I don't know how to get around it. I made a code sandbox for more context. And for reference I'm using the spacex api.
https://codesandbox.io/embed/gallant-mcnulty-lyied?fontsize=14&hidenavigation=1&theme=dark
Thanks in advance.
Upvotes: 2
Views: 798
Reputation: 5205
Because sometimes your function is called when data is null.
So you have to check that before accessing an element of that data:
console.log(props.data && props.data[5].mission_name);
Upvotes: 2
Reputation: 556
As you said, you are initially setting the data value to null. When the Card initially renders, it'll try to index 5 on null and give you that error. Try something like
if (props.data) { // the first render (where data is null) will skip this block
console.log(props.data[5].mission_name);
}
Upvotes: 2