React Native setState not a function
React Native setState not a function
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
this.setState({res: response});
this
2 Answers
2
This is lexical scope
issue. Use arrow function
.
lexical scope
arrow function
.then((response) => {
this.setState({ res: response });
})
It works thanks !
– BarbeBleue
Jun 29 at 9:57
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:
this
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);
});
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
use arrow function to wrap
this.setState({res: response});
that bringthis
inside arrow function– Pramendra Gupta
Jun 29 at 9:51