Reputation: 25
I fetch some JSON, add it to state (becoming an array of objects) and then try to console log the state. I'm able to successfully console log the array and an object in the array, but when I try to log a property of one of those objects it throws an error. Why is this?
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
function App() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
useEffect(() => {
fetch(
"https://my-json-server.typicode.com/typicode/demo/db" //test json data
)
.then((res) => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result.posts);
},
(error) => {
setIsLoaded(true);
setError(error);
}
);
}, []);
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
console.log(items); //works
console.log(items[1]); //works
//console.log(items[1].id); //Cannot read property 'id' of undefined
return <div></div>;
}
}
ReactDOM.render(
<React.StrictMode>
<h1> Test </h1>
<App />
</React.StrictMode>,
document.getElementById("root")
);
Upvotes: 1
Views: 540
Reputation: 25
When successfully receiving the result, swapping the order of setIsLoaded(true)
and setItems(result.posts)
has solved my problem. Still am curious as to why the order of the setStates caused the error.
Upvotes: 1