2
votes

I am trying to parse data from my Web API and show it on my react page, the connection is successful and the data is parsed (I can see an array of elements in the console) but whenever I want to show it on the page I get this error:

TypeError: Cannot read property 'map' of undefined.

I am using axios for the connection so here is my code:

import React from 'react';
import axios from 'axios';

class Player extends React.Component {
    state = {
      loading: true,
      error: "",
      data: []
  };  

  loadData = () => {
    this.setState({ loading: true });
    return axios
      .get('http://localhost:6444/api/example')
      .then(result => {
        console.log(result);
        this.setState({
          data: result.data.items,
          loading: false,
          error: false
        });
      })
      .catch(error => {
        console.error("error: ", error);
        this.setState({
          error: `${error}`,
          loading: false
        });
      });
  };

  componentDidMount() {
      this.loadData();
    }

    render() {
      const { loading, error, data } = this.state;
      if (loading) {
        return <p>Loading ...</p>;
      }
      if (error) {
        return (
          <p>
            There was an error loading the players.{" "}
            <button onClick={this.loadData}>Try again</button>
          </p>
        );
      }
      return (
        <div>
          <h1>Players</h1>
          <p>{data.map((player, index) => {
            return (
              <div key={index} player={player}></div>
            )})}</p>
        </div>
      );
    }   
}

export default Player;

I hope anyone can help me figure out the problem, I tried many things by now but nothing fixed the problem.

2
result.data.items is not returned in your response. You might want to try result.data.items || [] or add an error if it's empty.Acidic9
Can you also add what you see in console log when you do console.log(result)?Mukesh Soni
Can you post the output of console.log(result);?Prerak Sola
{data: Array(16), status: 200, statusText: "OK", headers: {…}, config: {…}, …} config: {url: "localhost:6444/api/example", method: "get", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), …} data: Array(16) {...} length: 16 proto: Array(0) headers: {content-length: "798", content-type: "application/json; charset=utf-8"} request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} status: 200 statusText: "OK" proto: ObjectJasmine
Is result.data.items also a non-empty array?Prerak Sola

2 Answers

1
votes

Based on your comment including the output of result, you should change your state update to:

this.setState({
  data: result.data,
  loading: false,
  error: false
});

Your data items must be directly on data, not under a key of data.items.

1
votes

There's no items property inside results.data. This should be enough.

this.setState({
  data: result.data,
  loading: false,
  error: false
});

Change the render for your div to put content inside the div

<p>{data.map((player, index) => {
  return (
    <div key={index}>{player}</div>
)})}</p>