0

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.

3 Answers 3

2

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

Comments

1

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>; })

2 Comments

That was so stupid of me to forget that. Thank you. But what about the point where console.log doesnt work?
@kalpeshshende: What "doesn't work" about it? What gets logged to the console? If it isn't what you expect, what is the object from which you're deriving it? Basically, when it "doesn't work" what is the value of props? What do you expect it to be? Why?
1

@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;

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.