skip to Main Content

Please help me with this

I just learn about ReactJs and now I learn about get data from Api, before that i use fetch to get api and it normal but when i use Axios and have that problem

import React, { Component } from 'react';
import './App.css';
import Axios from 'axios'
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {

    Axios({
      method: "GET",
      url: "https://reqres.in/api/users"
    }).then(res => {
      this.setState({
        isLoaded: true,
        items: res.data
      })
      console.log(res.data)

    }).catch(err => {
      console.log(err)

    })
  }

  render() {
    const { error, isLoaded, items = [] } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div>
          {items.map(function (item, i) {
            return <div key={i}>
              <p>{item.id}</p>
              <img src={item.avatar} alt="Card" />
            </div>
          })}
        </div>
      );
    }
  }
}

export default App;

This is data from reqres

    {"page":1,"per_page":3,"total":12,"total_pages":4,"data":
    [  {"id":1,"first_name":"George","last_name":"Bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"},
 {"id":2,"first_name":"Janet","last_name":"Weaver","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"},
  {"id":3,"first_name":"Emma","last_name":"Wong","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg"}
]}

Here is error from react

Error from react

I just want to show my data 🙁

2

Answers


  1. looks like res.data is not something you can loop over it. try to check what’s inside it

    edit:

    as you can see from you output:

    {"page":1,"per_page":3,"total":12,"total_pages":4,"data":
        [  {"id":1,"first_name":"George","last_name":"Bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"},
     {"id":2,"first_name":"Janet","last_name":"Weaver","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"},
      {"id":3,"first_name":"Emma","last_name":"Wong","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg"}
    ]}
    

    your informations are inside the data property, so, just loop over it:

     {items.data.map(function (item, i) {
                return <div key={i}>
                  <p>{item.id}</p>
                  <img src={item.avatar} alt="Card" />
                </div>
              })}
    
    Login or Signup to reply.
  2. Looking at the API response the statement should be

    items: res.data.data
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search