The following code is working fine...
const [showPosts, setShowPosts] = useState();
async function pullJson() {
const response = await fetch(apiUrl);
const responseData = await response.json();
displayData = responseData.map((el) => {
return <p key={el.id}>{el.title}</p>;
});
setShowPosts(displayData);
}
if i use {showPosts} in the "return" part, it will display a series of paragraph's with the "id" and the "title" values of the JSON BUT... I would like to navigate in the JSON data and access any value I want... so my idea was the following...
const [showPosts, setShowPosts] = useState();
async function pullJson() {
const response = await fetch(apiUrl);
const responseData = await response.json();
setShowPosts(responseData);
}
Now if I try to access {showPosts[12]} or {showPosts[12].id} I get an error like :
Unhandled Runtime Error
Error: Objects are not valid as a React child (found: object with keys {userId, id, title, completed}). If you meant to render a collection of children, use an array instead.
I know that objects are not valid as a react child... buut here, I have an array of object, I select and index (12) where my object is, and call an existing key (id) of this object.. Why does it throw this error... :s :s :s Thanks for your help !!
- I have tried to define my useState variable like an array..
const [showPosts, setShowPosts] = useState([]);
It doesn't work
- I have tried to define my useState variable like an array containing a default object
const [showPosts, setShowPosts] = useState([
{
userId: 1111,
id: 1111,
title: "delectus aut autem",
completed: false,
},
]);
Here it is strange... after the setShowPosts(displayData); which sets the state to the array of all my objects defined in the JSON, i'm able to call {showPosts[0].id}, but if i try to call the others like {showPosts[1].id} or {showPosts[2].id} i get an error : Server Error TypeError: Cannot read properties of undefined (reading 'id')