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")
);
items[1].idwhen you get the response inuseEffect()items[1] worksis it prints something? Orundefined?items[1].idthrows an error butitems[1].titleworks (try to log them one after each other)? I think that theconsole.log(items[1]);before the error returnsundefinedand this is because that maybeitemsis an empty array or it has only one item..items[1]returns the correct result (an object from the array, which shows the properties).items[1].titleanditems[1].idboth give the error "cannot read property (title/id) of undefined". Console logging the fetch results before the setstate (e.g. result.posts[1].id) works fine. Data source is (my-json-server.typicode.com/typicode/demo/db).