skip to Main Content

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


  1. 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])
    
    Login or Signup to reply.
  2. 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 as fireteam is an array.

    The following code will do it.

    import React, { useEffect, useState } from "react";
    
    const FireTeam = () => {
      const [fireteam, setFireTeam] = useState([]);
    
      useEffect(() => {
        const fetchData = async () => {
          const response = await fetch(`http://localhost:8080/fireteam/id/${localStorage.getItem("fireteamId")}`);
          const data = await response.json();
          setFireTeam([data]);
        };
    
        fetchData();
      }, []);
    
      return (
        <div>
          <div>
            {fireteam.map(fteam =>
              <div key={fteam.id}>
                <p>{fteam.name}</p>
              </div>
            )}
          </div>
        </div>
      );
    }
    
    export default FireTeam; 
    
    Login or Signup to reply.
  3. in case if you don’t want to change type of data to array, you can do something like this

    return (
        <div>
          <div>
            {Object.entries(fireteam).map(fteam =>
              <div key={fteam.id}>
                <p>{fteam.name}</p>
              </div>
             )}
        </div>
      </div>
    )
    

    you can read more here how it works

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search