Aniketh Saha
Aniketh Saha

Reputation: 913

how to map through json object in javascript?

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

Upvotes: 1

Views: 4712

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 282030

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

Upvotes: 3

Related Questions