0

I'm fetching data from an ExpressJS API.

The data returns and Object containing two Objects with the keys key1 and key2. These Objects contain Arrays of Objects as their values. If I print out the Arrays inside the HTML by doing {JSON.stringify(data["key1"])} I get all the data displayed as a stringified Array. When I'm trying to iterate over the data instead, it shows me a TypeError:

Uncaught TypeError: data.key1 is undefined

import React, { useEffect, useState } from "react";

export default function Home() {
    const [data, setData] = useState([]);

    const fetchData = () => {
        return fetch("http://localhost:1337/").then((response) => response.json()).then((data) => setData(data));
    }

    useEffect(() => {
        fetchData();
    }, []);

    return (
        <div class="h-screen">
            <div class="container mx-auto py-10 h-full text-white">
                {JSON.stringify(data["key1"])}
                {JSON.stringify(data["key2"])}
                {data["key1"].forEach(function(item, index) {
                    return <div>{item}</div>
                })}
            </div>
        </div>
    );
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
fullstacknoob
  • 161
  • 1
  • 7
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Jan 16 '23 at 13:50
  • `data` is an empty array until the `fetch` is completed. You need to program as if `data` is the initial value you provide to `useState`. – Heretic Monkey Jan 16 '23 at 13:51
  • return null when data was null and then render you data. – Manish Jha Jan 16 '23 at 13:53

1 Answers1

0
 const [data, setData] = useState([]);

Here you set the initial value of data as [] so no key1, key2 keys are not defined.

Initially, when your component renders

value of data is [] so you get an undefined error for key1 and key2.

You can solve this problem by adding check on data

{data.length > 0 &&  
    <div class="container mx-auto py-10 h-full text-white">
       {JSON.stringify(data["key1"])}
       {JSON.stringify(data["key2"])}
       {data["key1"].forEach(function(item, index)
           return <div>{item}</div>
        })}
     </div>
 }

This will solve your problem.

Neha
  • 1
  • 2