Reputation: 45
Can someone explain me why this.setState is not a function ?
I do not see why my code has an error
import React from 'react';
import axios from 'axios'
import { StyleSheet, Text, View , Image} from 'react-native';
export default class App extends React.Component {
constructor(){
super();
this.state = {res: []}
}
componentDidMount() {
axios.get('https://api.github.com/repos/torvalds/linux/commits')
.then(function (response) {
this.setState({res: response});
}).catch(function (error) {
console.log(error);
});
}
}
Thank you
Upvotes: 2
Views: 193
Reputation: 15292
This is lexical scope
issue. Use arrow function
.
.then((response) => {
this.setState({ res: response });
})
Upvotes: 4
Reputation: 3316
The reason for the error is this
does not refer to component class context within resolver function of axios. You can either have resolver function as fat arrow function for your code to work, something like below:
componentDidMount() {
axios.get('https://api.github.com/repos/torvalds/linux/commits')
.then((response) => {
this.setState({res: response});
}).catch(function(error) {
console.log(error);
});
}
or you can change it to something like below:
componentDidMount() {
let self = this;
axios.get('https://api.github.com/repos/torvalds/linux/commits')
.then(function(response) {
self.setState({res: response});
}).catch(function(error) {
console.log(error);
});
}
Upvotes: 2