'Property undefined - Can't get call fetched JSON object 2 times

I am trying to pass fetched & parsed JSON data I stored in a variable from my file App.js to a component via props (but the same bug also occurs if I only want to console.log the data) in Chrome. But I can not pass or console.log the data more than one time without getting the error message: "Uncaught TypeError: Cannot read properties of undefined (reading 'title')".

This is my code in App.js:

import './App.css';
import React, { useEffect, useState } from 'react';
import SpentTimeItem from './components/SpentTimeItem';

function App() {
  const [jsonData, setJsonData] = useState([{}]);
  const fetchData = () => {
    fetch('data.json', {
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
    })
      .then((res) => res.json())
      .then((data) => {
        setJsonData(data);
      });
  };
  useEffect(() => {
    fetchData();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  console.log('App.js jsonData[0].title', jsonData[0].title);
  console.log('App.js jsonData[1].title', jsonData[1].title);

  return (
    <div className="App">
      <header className="App-header"></header>
{/*This is the buggy part. Calling it once with jsonData[0] works, but as soon as I do it a second time with jsonData[1], nothing works anymore.*/}
      {jsonData && <SpentTimeItem passedJsonData={jsonData[0]} />}
      {jsonData && <SpentTimeItem passedJsonData={jsonData[1]} />}
    </div>
  );
}

export default App;

The error (main) error message in Chrome is: "Uncaught TypeError: Cannot read properties of undefined (reading 'title')". I don't know why it's not working, my only guess is, that it has to do something with the re-rendering of the page and that the data is somehow gone once I call the stored parsed JSON data a second time.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source