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 !