1

I want to map(loop) through the each attribute of the JSON object . the JSON looks like this

[
  {
    "_id": "5ad5c0ccdec0fa2b3c1f1ba0",
    "name": "optioin",
    "job": "google",
    "location": "usa",
    "gender": "male",
    "__v": 0
  },
  {
    "_id": "5ad6043f9fba4125b467c6af",
    "name": "reactjs",
    "job": "facebook",
    "location": "california",
    "gender": "male",
    "__v": 0
  }
]

I want this JSON to be assign to my reactjs state my component looks like this

  componentDidMount() {
      fetch('/api/get/all').then((res)=>{
        return res.json();
      }).then(users =>{
          this.setState({
            user: users
          })
      });
      console.log(this.state.user);
  }

I have initialize my user state as

this.state={user:[]};

the API is responding from node server like this

app.get('/api/get/all',(req,res)=>{
    User.find({},(err,data) => {
      // res.json("inside this");
      if (err) {
        // console.error(err);
        res.json({
          message:"error"
        });
      }
      // console.log(data.toArray);

      res.json(data);
 });
});

I want to get each value for the each JSON object my mapping function

<div className="row">

                {this.state.user.map(u =>{
                    <UserDiv name={u.name} age={u.age} location={u.location} gender={u.gender} job={u.job} />
                })}



            </div>

error i am getting is

this.state.user.map is not a function

result of console.log(this.state.user)

(2) [{…}, {…}]0: {_id: "5ad5c0ccdec0fa2b3c1f1ba0", name: "optioin", job: "pubg", location: "usa", gender: "male", …}1: {_id: "5ad6043f9fba4125b467c6af", name: "reactjs", job: "facebook", location: "california", gender: "male", …}length: 2__proto__: Array(0)

thanks in advance

Aniketh Saha
  • 843
  • 10
  • 22

1 Answers1

3

You are not setting the state correctly in response to your API call, you need to write this.setState({user: users}) and not this.setState({user: u})

componentDidMount() {
      fetch('/api/get/all').then((res)=>{
        return res.json();
      }).then(users =>{
          this.setState({
            user: users
          })
      });
      // console.log(this.state.user);  <-- This won't show update state since setState is asynchronous
  }

Note: You can check this answer on more details about setState being asynchronous

Chirag Ravindra
  • 4,760
  • 1
  • 24
  • 35
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400