React JS : this.setState and JSON.parse
React mounting component lifecycle is:
- constructor
- componentWillMount
- render
- componentDidMount
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>
);
}
}
Related videos on Youtube
Rbejot
I'm studying development at 42 since 2 years (a french school without professors!). I'm actually CTO of a young startup. We are using a full JS stack.
Updated on June 04, 2022Comments
-
Rbejot almost 2 years
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 !
-
Supun Abesekara almost 6 yearsHow i do it with fetch?
-
Nik almost 6 years@SupunAbesekara you can just replace GetData with window.fetch and use promise chaining e.g.:
window.fetch(url, data).then(result => result.json()).then(json => this.setState({users: json.users});