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>
);
}