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

3
  • Looks like there is a typo in your componentDidMount method. Perhaps you want to do user: users instead of user: u Commented Apr 18, 2018 at 7:11
  • this.setState({ user: u }) may be you want to use this.setState({ user: users }) Commented Apr 18, 2018 at 7:11
  • yeah there is a typo error but i did it with users also ...still no hope Commented Apr 18, 2018 at 7:17

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

11 Comments

Any reason why res => res.json is written in a more verbose way?
@sabithpocker, the way that you suggest is another way to write (res)=>{ return res.json(); } , you can prefer whatever you feel is the best, There is not performance difference, you can check stackoverflow.com/questions/49425755/…
@Shubham I changed that that was typo error in this question but in my code I changed that to users but still same error
@AnikethSaha, can you check if Array,isArray(users) gives true in success function
@ShubhamKhatri it is returning true
|

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.