Home > Enterprise >  how to render list in react using api
how to render list in react using api

Time:06-25

enter image description here>Aim

To render the list fetched from dummy API.

The Code

App.js

import logo from './logo.svg';
import Header from './components/Header';
import MapArea from './components/MapArea';
import Card from './components/Card';
import './App.css';
import React from "react";
class App extends React.Component {
  constructor(e){
    super();
    this.state = {
      menu:false,
      userData:[]
    }
  }

  componentDidMount() {
    fetch("https://reqres.in/api/users?page=2")
    .then((a)=>{return a.json()})
    .then((b)=>{
      this.setState({
        userData:b
      })
    })
  }



Card.js

function Card(props){
let userData = props.data.userData.data;
    console.log(userData) //Sometimes WORKING FINE
    return(<div>{userData.map((item)=>{<h1 key={item.id}>item.id</h1>})}</div>)
}
export default Card;

The Problem

Now the thing is that sometimes the console.log works and sometimes it doesnt. Then I have to remove the javascript "{}" in render method of the Card.js and save and again paste it back and save. I have also added image of console when the console.log doesnt work

Also the list doesnt render.

CodePudding user response:

Your initial state is wrong. The dummy api returns the array under the "data" field, so you need to match that structure in the initial state.

    this.state = {
      menu:false,
      userData:{ data: [] }
    }

CodePudding user response:

The callback for .map() isn't returning anything. Arrow functions only have an implicit return if there are no curly braces surrounding the function. So either remove the curly braces:

userData.map((item) => <h1 key={item.id}>item.id</h1>)

or add an explicit return:

userData.map((item) => { return <h1 key={item.id}>item.id</h1>; })

CodePudding user response:

@kalpeshshende your console.log is "not working" because your initial state doesn't have the same structure as the json returned from the API. I recommend changing your componentDidMount

componentDidMount() {
    fetch("https://reqres.in/api/users?page=2")
    .then((a)=>{return a.json()})
    .then((b)=>{
      this.setState({
        userData:b?.data ?? []
      })
    })

and the inside the component: let userData = props.data.userData; or const {userData} = props.data;

  • Related