I have a problem, I don't know how I can fix it. I am doint a request to my api and it responds with an object like this :
{"_id":"5a806648300caf0072c7254a","mail":"[email protected]"}
I want to print to my react component the mail. In my "componentDidMount()" function I get the mail, so there is no problem with my api. But when I want to set the state of my "users" variable, I can not print the variable in my component... It says that it's undefined.
Here is my code :
class UserList extends Component {
constructor(props){
super(props);
this.state = {users:[]}
}
componentDidMount() {
//here my function that store the response from my api
GetData('http://localhost:3333/users', 'username=admin',
(res) =>
{
this.setState({users: JSON.parse(res)});
//Here I can log the mail
console.log(this.state.users[0].mail);
})
}
render() {
return (
<table>
<thead>
<tr>
<th>EMAIL</th>
</tr>
</thead>
<tbody>
<tr>
//Here it is 'undefined'
<td>{this.state.users[0].mail}</td>
</tr>
</tbody>
</table>
);
}
}
Thank you for your help !
React mounting component lifecycle is:
See more here: https://reactjs.org/docs/react-component.html#mounting
When your component is mounting this.state.users is an empty array.
You can change the render method:
class UserList extends Component {
constructor(props){
super(props);
this.state = {users:[]}
}
componentDidMount() {
//here my function that store the response from my api
GetData('http://localhost:3333/users', 'username=admin',
(res) =>
{
// After setState react runs updating lifecycle methods (https://reactjs.org/docs/react-component.html#updating)
this.setState({users: JSON.parse(res)});
//Here I can log the mail
console.log(this.state.users[0].mail);
})
}
render() {
// if users are not loaded, we return null from render function
if (this.state.users.length === 0) {
return null;
}
return (
<table>
<thead>
<tr>
<th>EMAIL</th>
</tr>
</thead>
<tbody>
<tr>
<td>{this.state.users[0].mail}</td>
</tr>
</tbody>
</table>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With