Amimaro Amimaro -4 years ago 70
React JSX Question

Different output fetching json with and without arrow function on reactjs

Why I am getting different responses when fetching json? When I use arrow function it works and when not it doesn't work.

constructor(props){
super(props);
this.state = {
data: [],
};
this.url = 'https://fcctop100.herokuapp.com/api/fccusers/top/recent';
}


Fetch with arrow function:

fetch(url)
.then((response) => {
return response.json()
}).then((json) => {
this.setState({data: json});
console.log('parsed json', json)
}).catch((ex) => {
console.log('parsing failed', ex)
});


Returns on console:

parsed json Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, 90 moreā€¦ ]


And when I don't use arrow function the output is different:

fetch(url)
.then((response) => {
return response.json()
}).then(function(json) {
this.setState({data: json});
console.log('parsed json', json)
}).catch((ex) => {
console.log('parsing failed', ex)
});


Returns this:

parsing failed TypeError: this is undefined Stack trace:
listCampers/<@http://localhost:3000/static/js/bundle.js:18177:17

Answer Source

arrow function does not have own this and refers to parent scope(in this case it is React component). If you use function you have to set this by you own, because in this case this refers to global scope(in browser it is window) or if you use strict mode this will be undefined

.then(function(json) {
  this.setState({data: json});
  console.log('parsed json', json)
}.bind(this))
 ^^^^^^^^^^^
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download