1

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 !!

  1. I have tried to define my useState variable like an array..
const [showPosts, setShowPosts] = useState([]);

It doesn't work

  1. 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')

4
  • Since you have an array of objects and all objects are sitting on position 0 i.e showPosts[0].id that's why you have an error of cannot read properties of undefined.
    – Asma
    Mar 14 at 8:02
  • Why do you say all objects are on position 0 ? When I do setShowPosts(responseData); showPosts is like [{ .... }, { .... }, { .... }, { .... }, ....]
    – Edouard
    Mar 14 at 8:23
  • all objects are in position zero, because objects are adding more and more, not the array's position. Array's are like [1,2,3] , now think of all your objects are placing like this : [{.....},2,3]
    – Asma
    Mar 14 at 8:27
  • I've made some console.log... ...It is not the case... ...I think it is more a problem useState... ...but I dont understand, because I do a useEffect first...
    – Edouard
    Mar 14 at 13:21

1 Answer 1

1

TL;DR: I’d search for all the usages of showPosts and make sure they have been changed to showPosts[index]?.id. If element at index doesn’t exist on showPosts you would get Cannot read properties of undefined (reading 'id'). This could happen if showPosts is initialized to an empty array, since it would be empty until the fetch completes.

You could either use optional chaining showPosts[index]?.id or do something like showPosts.map(post => id).

—-

It looks like responseData has the following structure [ { id: string, title: string } ], so it’s a JSON array of objects where each object has an id an a title.

In your first code snippet, responseData is converted from an array of JSON objects to an array of JSX <p> tags:

displayData = responseData.map((el) => {
          return <p key={el.id}>{el.title}</p>;  })

displayData can then be inserted anywhere in JSX document using {{showPosts}}, since it is also JSX.

In you second code snippet, showPosts is now an array of JSON objects and React cannot render JSON objects. So when React tries to render the individual objects in the showPosts array you get 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.

Also in your second scenario showPosts is initialized to empty array, so an empty array will be rendered until data is returned from fetch (which might take a few seconds). When you try to access element at index 12 of this empty array this element would be undefined (since the array has 0 elements), and you cannot read property id of an undefined object. Optional chaining or conditional rendering can be used here to only access id when an element at index 12 exists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.