I am building my first React app using Java Spring for the backend. I encountered an issue while trying to fetch data from the API and map it in js. It gives me the error fireteam.map is not a function
. Here is the problem code:
import React, { useEffect, useState } from "react";
const FireTeam = () =>{
const [fireteam, setFireTeam] = useState([]);
useEffect(() => {
fetch(`http://localhost:8080/fireteam/id/${localStorage.getItem("fireteamId")}`)
.then(response => response.json())
.then(data => {setFireTeam(data)})
});
return (
<div>
<div>
{fireteam.map(fteam =>
<div key={fteam.id}>
<p>{fteam.name}</p>
</div>
)}
</div>
</div>
)
}
export default FireTeam
using console.log
at the end of the fetch request to check the data gave me the correct data:
{id: 3, name: 'Intercessors', description: 'fdgdfsggfsd', killTeamId: 1}
So it’s not an issue with how i built my fetch request. I thought it might boil down to timing issues between the fetch()
and Javascript trying to map before the data was set, so i tried putting the fetch request in an async/await function and calling it in the UseEffect block, but the problem persists.
Gazes is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.