skip to Main Content

I have been scouring over similar questions and can’t find any that have been answered for this exact api. I know its really easy I’m just loosing my mind right now.. I just need a list of all the users from the reqres api.. if you have a look at the code below it explains what data I’m getting in the console logs. All I want to do is to render that as a list in the render method:

import React, { Component } from "react";
import axios from "axios";

class User extends Component {
  state = {
    people: []
  };

  componentDidMount() {
    axios
      .get("https://reqres.in/api/users")
      .then(response => {
        this.successShow(response);
      })
      .catch(error => {
        this.successShow(error);
      });
  }

  successShow(response) {
    this.setState({
      people: response.data.data
    });
  }

  render() {
    console.log(this.state.people[0]);
    //this console log prints this:
    //{id: 1, first_name: "George", last_name: "Bluth", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"}

    console.log(this.state.people[1]);
    //this console log prints this:
    //{id: 2, first_name: "Janet", last_name: "Weaver", avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"}

    return <div>HOW DO I RENDER A LIST OF ALL THE USERS HERE??</div>;
  }
}
export default User;

2

Answers


  1. You can use map() on this.state.people

    return (
      <ul>
        {this.state.people.map(({id, first_name, last_name, avatar}) => (
          <li key={id}>
            First Name: {first_name} Last Name: {last_name} avatar: {avatar}
          </li>))
        }
      </ul>
    );
    
    Login or Signup to reply.
  2. in your render() method just iterate through your people object, for example like that:

    render() {
      return (
        <ul>
          {this.state.people.map(person => (
            <li key={person.id}>{person.firstName}</li> 
          )}
        </ul>
      )
    }
    

    Just don’t forget to use keys on iterated values

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