import React, { useEffect, useState } from 'react';
function MainContent() {
const [objectsArr, setObjectsArr] = useState(null);
useEffect(() => {
async function fetchMyAPI() {
let response = await fetch('http://localhost:3030/pickedObjects')
response = await response.json();
setObjectsArr(response)
}
fetchMyAPI()
}, [])
const contentDiv = document.getElementsByClassName('content')[0];
return (
<ul className="content row">
{objectsArr.map((item) => {
return (
<ContentItem className="item" item={item} />
)
})}
</ul>
);
}
export default MainContent;
I am trying to render an array of elements, using useEffect that calls a fetch, and the I use .map() to directly render them
So when I try to run this I get an error:
Uncaught TypeError: Cannot read properties of null (reading ‘map’)
which is a setObjectsArr initial value. So is the setObjectsArr(response) in the useEffect not being set, or it’s being set too early?
How can I fix that?
I tried almost everything but I cant find the reason why it doesn’t work.The fetch itself is okay, it returns a decent value, but useState doesn’t set it.