I am using simple react component. Here is the code.
import React from 'react';
export default class UserProfile extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
name: 'ALok'
}
}
componentDidMount()
{
fetch ('https://jsonplaceholder.typicode.com/users')
.then (response => response.json())
.then (res => this.setState({ posts : res}));
}
render() {
return (
<div>
<h1>{this.state.posts.length}</h1>
</div>
)
}
}
This code works. But If I try to add multiple instruction at
componentDidMount()
{
fetch ('https://jsonplaceholder.typicode.com/users')
.then (response => response.json())
.then (res => this.setState({ posts : res}));
to something like this
componentDidMount() {
fetch ('https://jsonplaceholder.typicode.com/users')
.then (response => {
// adding multiple line
response.json();
console.log ('Custom Log');
})
.then (res => this.setState({ posts : res}));
}
It stop working. It gives an error
You need to return a promise as part of the promise chain. Other than that, the {}
are just normal JS scoping, functional scoping in this case. You were implicitly returning undefined
and that was being assigned to res
in the next thenable and saved into state.
componentDidMount() {
fetch ('https://jsonplaceholder.typicode.com/users')
.then (response => {
// adding multiple line
console.log ('Custom Log');
return response.json();
})
.then (res => this.setState({ posts : res}));
}