1

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")
);
5
  • Try to log items[1].id when you get the response in useEffect() Commented Dec 5, 2020 at 18:35
  • When you say items[1] works is it prints something? Or undefined? Commented Dec 5, 2020 at 18:43
  • I can console log "result.posts[0].title" successfully after getting the result, I haven't tried after the setstate (don't know how to). Items and items[1] does print successfully in the above code. Commented Dec 5, 2020 at 18:51
  • So items[1].id throws an error but items[1].title works (try to log them one after each other)? I think that the console.log(items[1]); before the error returns undefined and this is because that maybe items is an empty array or it has only one item.. Commented Dec 5, 2020 at 19:07
  • items[1] returns the correct result (an object from the array, which shows the properties). items[1].title and items[1].id both 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). Commented Dec 5, 2020 at 19:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.