React JS - Unable to bind API data to this.setState in React JS using fetch

Here is the code

class Users extends Component {

constructor(){
super();
this.state={users:[]};
}

componentDidMount(){

fetch('http://some_ip_address/api/subuserlist',{
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'filterfield': 'group_id',
    'filtervalue': 'random_filter_value'
  }
}).then(result=>result.json())
 .then(function(data) {
   //console.log(data);                     //able to print data
     this.setState({users:data});
 }, () => {
           if (this.state.users.length > 0) {
             console.log(this.state.users[0].firstName);
           }else{
             console.log('in else');                            // going to else
           } 
      })
.catch(function(error) {
  // If there is any error you will catch them here
});   

}

render() {
return (

              <tbody>{this.state.users && this.state.users.map(function(users) {                    
                      return (
                          <tr>
                              <td>{users.firstName}</td>
                          </tr>
                        )                     
                    })}</tbody>          
);
 }
}

export default Users;

Can some body help? Am not getting any data in this.state.users

If I’m not mistaken the issue you are having is this: the this anonymous function inside the then() that contains this.setState() is not the React component—if you have a look at the errors in the console you should see that an error related to that.

In this case you should be using an arrow function (since you are already using arrow functions), because this inside an arrow function refers to the this of its enclosing block of code (I hope I’ve gotten the wordings right here!), which is the this of the React component.

A few other things I’ve spotted:

  • I don’t think you should see “in else” logged at all if there are no errors, are you sure that you are seeing it?
  • this.state.users is actually always true—[] is a truthy value (so is {}). The corresponding part in your code is therefore redundant

I hope that helps!