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.
>Solution :
Your data is not an array but an object, so using map() won’t work.
map() is a function that only exists for arrays, just like filter(), reduce(), forEeach(), etc. That’s why you have the "is not a function" error.
You need to either make sure you api sends an array, like this :
[{id: 3, name: 'Intercessors', description: 'fdgdfsggfsd', killTeamId: 1}]
Or if you’re sure you’ll always have just an object, do :
setFireTeam([data])