Home > OS >  Array is appearing in console.log() but will not render in react? Using useEffect hook
Array is appearing in console.log() but will not render in react? Using useEffect hook

Time:12-10

import React, { useEffect, useState } from "react";
import { useGetTeamQuery } from "./store/teamsApi"


function TeamList(props) {
    const team_names = []
    console.log("GET ALL TEAMS", props.props.items)
    

    useEffect(() => {
        const fetchData = async () => {
            for (let i = 1; i < 31; i  ) {
                const res = await fetch(
                    `http://sports.core.api.espn.com/v2/sports/football/leagues/nfl/seasons/2022/teams/${i}?lang=en&region=us`
                    );
                const json = await res.json();
                console.log("JSON", json)
                team_names.push(json.displayName)
        }};
        fetchData();

        }, [team_names]);
    console.log("DATA", team_names)


    return (
        <>
        <div className="container">
            <h1>Team List</h1>
            <div>
            <ol>
                {console.log("DATA 2", team_names)}
                {team_names.map(team => (
                    <li>{team}</li>
                ))}
            </ol>
            </div>
        </div>
        </>
    )
}


export default TeamList;

There are no errors, but no code being rendered outside of the tags.

Have tried using numerous tags, and tried different changes to the useeffect function as well. Because list appears as intended is the "DATA 2" console.log, my thinking is the issue is the block of code below this. I'm not sure how to reformulate this map:

                {team_names.map(team => (
                    <li>{team}</li>
                ))}

CodePudding user response:

You should use useState to save the response from the API.

So here's your solution:

import React, { useEffect, useState } from "react";
import { useGetTeamQuery } from "./store/teamsApi";

function TeamList(props) {
  const [team_names, setTeam_names] = useState([]);

  useEffect(() => {
    async function fetchData() {
      try {
        for (let i = 1; i < 31; i  ) {
          const response = await fetch(
            `https://sports.core.api.espn.com/v2/sports/football/leagues/nfl/seasons/2022/teams/${i}?lang=en&region=us`
          );
          const json = await response.json();
          setTeam_names((team_names) => [...team_names, json.displayName]);
        }
      } catch (e) {
        console.error(e);
      }
    }
    fetchData();
  }, []);

  return (
    <>
      <div className="container">
        <h1>Team List</h1>
        <div>
          <ol>
            {team_names.map((team, i) => (
              <li key={i}>{team}</li>
            ))}
          </ol>
        </div>
      </div>
    </>
  );
}

export default TeamList;

It's live in the codesandbox: https://codesandbox.io/s/admiring-liskov-1vmzd7?file=/src/TeamList.js

  • Related