1

I'm trying to iterate throw elements in a Array of objects, but since the returned data is not an Array but a Object, .map() can't be used in the simple way.

API returns the following structure

/players (endpoint)

{
  "players": [
    {
      "player_id": "Uy2sZ5ef",
      "player_name": "Foo",
      "player_team": "5c50bae023213348c4453aaf"      
    },
    {      
      "player_id": "h15sqI4D",
      "player_name": "Foo 2",
      "player_team": "5c50bae023213348c4453aaf"
    }
  ]
}

React component

export class Players extends Component {
    state = {
        players: []
    }

    componentDidMount() {
    API.get(`players/`).then(res => {
            console.log(res)
            this.setState({ players: res.data })
        })
    }

    render() {
        return (
            <section className="contents">

                { this.state.players.map(player => <li>{player.player_name}</li>)}

            </section>
        );
    }
}

Console error

2 Answers 2

7

If your data looks like that object, and you need only players, you should:

    componentDidMount() {
    API.get(`players/`).then(res => {
            console.log(res)
            this.setState({ players: res.data.players }) // <-- get only the players
        })
    }
Sign up to request clarification or add additional context in comments.

1 Comment

That's correct, I was unable to find it. After Stackoverflow's delay to accept this answer, I'll do it :)
1

You might be interested in functional component:

const Players = () => {
  const [players, setPlayers] = useState([]);

  useEffect(() => {
    API.get(`players/`).then(res => {
      console.log(res);
      setPlayers(res.data.players); // <-- get only the players
    });
  }, []);

  return (
    <section className="contents">
      {players.map(player => (
        <li>{player.player_name}</li>
      ))}
    </section>
  );
};

1 Comment

Indeed we all should work with functional components !

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.