cubila
cubila

Reputation: 53

Cannot read property 'map' of undefined on useState value

I'm new to react, I'm getting this error constantly and after google some I can't find the reason why the useState value can't be read as array :( ... this the error I'm getting: 'TypeError: team.map is not a function'

    import React, { useEffect, useState } from "react";

    const SportTeams = () => {
      const [team, setTeam] = useState([]);

      useEffect(() => {
        const getSports = async () => {
          const response = await fetch("https://www.thesportsdb.com/api/v1/json/1/all_sports.php");
          const data = await response.json();
          setTeam(data);
          console.log(data);
        }
        getSports();
      }, []);

      return (
        <div className="myClass">
          <ul>
            {team.map((sport, index) => {
              return <li key={`${sport.strSport}-${index}`}>{sport.strSport}</li>
            })}
          </ul>
        </div>
      );
    };
    export default SportTeams;

Upvotes: 1

Views: 938

Answers (3)

Junius L
Junius L

Reputation: 16152

As I said in my comment. the value you are setting to teams isn't an array.

enter image description here

const data = await response.json();
setTeam(data.sports);

Upvotes: 0

Mukarram Javid
Mukarram Javid

Reputation: 89

Just update setTeam like following, your error will be resolved.

setTeam(data.sports);

enter image description here

Upvotes: 1

Yadab
Yadab

Reputation: 1883

It is because you are setting the team state with the data without checking if its undefined. If the data is undefined your state team become undefined as well. So make sure to check the data.

    import React, { useEffect, useState } from "react";

        const SportTeams = () => {
          const [team, setTeam] = useState([]);

          useEffect(() => {
            const getSports = async () => {
              const response = await fetch("https://www.thesportsdb.com/api/v1/json/1/all_sports.php");
              if (response) {
                const data = await response.json();
                if (data) {
                  setTeam(data);
                }
              }
              console.log(data);
            }
            getSports();
          }, []);

          return (
            <div className="myClass">
              <ul>
                {team.map((sport, index) => {
                  return <li key={`${sport.strSport}-${index}`}>{sport.strSport}</li>
                })}
              </ul>
            </div>
          );
        };
        export default SportTeams;

There might also be the chance that your response is not what you expected and the actual data might be inside your response. In that case you need check what your response first then proceed to set the data.

Upvotes: 0

Related Questions