J.Doe
J.Doe

Reputation: 25

Can't access property of array of objects after fetch

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

Answers (1)

J.Doe
J.Doe

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

Related Questions