1

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.

6
  • 1
    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. Commented Aug 14, 2019 at 8:15
  • Can you also add what you see in console log when you do console.log(result)? Commented Aug 14, 2019 at 8:15
  • Can you post the output of console.log(result);? Commented Aug 14, 2019 at 8:16
  • {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: Object Commented Aug 14, 2019 at 8:17
  • Is result.data.items also a non-empty array? Commented Aug 14, 2019 at 8:18

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

4 Comments

I tried to change it and now I don't get the error anymore but the data is not displayed
Because there's nothing inside the div for player.
@MukeshSoni hes retrieving the items not all data!
Yes. My answer has fixes for both the problems. The first code removes access to result.data.items.
1

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.

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.