1

I'm trying to use an api with football teams, I want to simply render the name of the teams in a div or a list. But it just render the last one.

When I console.log it, it shows all the teams

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      teams: [],
      isLoaded: false
    }
  }
  componentDidMount() {
    fetch('https://www.thesportsdb.com/api/v1/json/1/search_all_teams.php?l=English%20Premier%20League')
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          data: json,
        })
      })
  }
  render() {
    var {
      isLoaded,
      data
    } = this.state;
    if (!isLoaded) {
      return <div> Loading... < /div>
    } else {
      for (var key in data.teams) {
        if (data.teams.hasOwnProperty(key))
          console.log(data.teams[key].strTeam)
      }
      return ( <div className = "App" >
        Premier League Teams!{
          data.teams[key].strTeam
        } </div>
      );
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

1

2 Answers 2

2

Try this:

return (
    <div className="App">
        Premier League Teams!{data.teams.map(team => team.strTeam)}
    </div>
);

This will loop through the teams array with map and render each one.

Sign up to request clarification or add additional context in comments.

1 Comment

please accept the answer by clicking the arrow next to the answer.
1

Try this,

import React from "react";

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      teams: [],
      isLoaded: false
    };
  }

  componentDidMount() {
    fetch(
      "https://www.thesportsdb.com/api/v1/json/1/search_all_teams.php?l=English%20Premier%20League"
    )
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded: true,
          data: json
        });
      });
  }

  render() {
    var { isLoaded, data } = this.state;

    if (!isLoaded) {
      return <div>Loading... </div>;
    } else {
      return (
        <div className="App">
          Premier League Teams!
          {data.teams.map(team => (
            <div> {team.strTeam} </div>
          ))}
        </div>
      );
    }
  }
}
export default Test;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.