Home > OS >  React: How to get first item's data in a fetched JSON file
React: How to get first item's data in a fetched JSON file

Time:10-27

I'm trying to fetch the data from the first object in a JSON file.


const apiUrl =
  'https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean';

function App() {
  const [items, setItems] = useState([]);

  useEffect(() => {
    async function fetchData() {
      await fetch(apiUrl)
        .then((res) => {
          return res.json();
        })
        .then((data) => {
          setItems(data.results);
          console.log(data.results);
        })
        .catch((error) => {
          console.log(error);
        });
    }
    fetchData();
  }, []);

  return (
    <div>
      <h2>First Item Category: {items[0].category}</h2>
    </div>
  );
}

export default App;

However, I keep getting the error "TypeError: Cannot read properties of undefined (reading 'category')."

Can anyone help me wrap my head around the issue? Thank you!

CodePudding user response:

you need to do a check for the existence of items, since the component is rendered before the end of the request

  if(!items.length) return <></> {/*u can use loader here*/}
  return (
    <div>
      <h2>First Item Category: {items[0].category}</h2>
    </div>
  );

or

  return (
    <div>
      <h2>First Item Category: {items[0]?.category}</h2>
    </div>
  );
  • Related