Using arrow function in React JS - Callback

Using arrow function in React JS - Callback

When you need to perform setState in a callback function, for example call api and update the data as below

1
2
3
4
5
6
7
8
9
10
axios.get('http://yourdomain/api/get-data')
.then(function (response) {
// handle success
this.setState({
data: response.data
})
})
.catch(function (error) {
// handle error
})

Using the usual callback function like this you will get an error that this.setState is not a function
To fix this you usually create a variable outside the callback function to store this pointer as below

1
2
3
4
5
6
7
8
9
10
11
const that = this
axios.get('http://yourdomain/api/get-data')
.then(function (response) {
// handle success
that.setState({
data: response.data
})
})
.catch(function (error) {
// handle error
})

However, you can also handle this problem by using the arrow function

1
2
3
4
5
6
7
8
9
10
axios.get('http://yourdomain/api/get-data')
.then((response) => {
// handle success
this.setState({
data: response.data
})
})
.catch((error) => {
// handle error
})

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×