-2

When I'm trying to set my "users" state's variable, I've got the following message :
Cannot read property 'setState' of undefined
It's on the following code line :

this.setState({users: data.users});

Here is my class

` import React, { Component } from 'react';

class Users extends Component {

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

componentWillMount() {
    this.getUsers();
}

getUsers = () => {
    let myHeaders = new Headers({
        'Authorization': 'Basic '+btoa('john@doe.com:password'),
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    });

    fetch('https://dev-api/v1/user/', {
        method: 'GET',
        headers: myHeaders
    }).then(function(response) {
        if (!response.ok) {
            throw Error(response.statusText);
        }
        return response;
    }).then(function(response) {
        response.json().then(function(data) {
            this.setState({users: data.users});
        });
    }).catch(function(error) {
        console.log(error);
    });
}

render() {
    return (
        <table className="striped bordered">
            <thead>
                <tr>
                    <th>email</th>
                    <th>Firstname</th>
                    <th>Lastname</th>
                </tr>
            </thead>
            <tbody>
            {this.state && this.state.users && this.state.users.map(user =>
                <tr>
                    <td>{user.username}</td>
                    <td>{user.firstname}</td>
                    <td>{user.lastname}</td>
                </tr>
            )}
            </tbody>
      </table>
    );
}

}

export default Users;`

Thanks a lot !

banibanc
  • 143
  • 3
  • 16

1 Answers1

2
constructor(props) {
    super(props);
    this.state = {
        users: []
    };
   this.getUsers = this.getUsers.bind(this); //************ add this
}

getUsers = () => {
    let self = this //************ add this
    let myHeaders = new Headers({
        'Authorization': 'Basic '+btoa('john@doe.com:password'),
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    });

    fetch('https://dev-api/v1/user/', {
        method: 'GET',
        headers: myHeaders
    }).then(function(response) {
        if (!response.ok) {
            throw Error(response.statusText);
        }
        return response;
    }).then(function(response) {
        response.json().then(function(data) {
            self.setState({users: data.users}); //****** replace this
        });
    }).catch(function(error) {
        console.log(error);
    });
}
Piyush Dhamecha
  • 1,485
  • 1
  • 13
  • 22