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.
3
Answers
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 :
Or if you’re sure you’ll always have just an object, do :
Your given example of the
console.log
is not an array. But the map function is used for array manipulation. To fix this you can ensure the data obtain asfireteam
is an array.The following code will do it.
in case if you don’t want to change type of data to array, you can do something like this
you can read more here how it works