Reputation: 164
It is telling me this.setState' is undefined, but i'm not sure what I can do to make "this" refer to the proper context for setState. I don't know what else I can bind to help.
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import axios from 'react-native-axios';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: 50
}
this.apirequest = this.apirequest.bind(this);
}
componentWillMount() {
this.apirequest();
}
apirequest() {
axios.get('http://api.openweathermap.org/data/2.5/weather')
.then(function (response) {
console.log(response.data.main.temp);
this.setState({
data: response.data.main.temp
})
})
.catch(function (error) {
console.log(error);
});
}
Upvotes: 1
Views: 3662
Reputation: 174
Try replacing your function by using a ES6 fat arrow function
instead of
.then(function (response) {...
do
.then(response => { ...
This works because fat arrow functions do not redefine the definition of this
, therefore the value of this
is still the originating context
Upvotes: 3
Reputation: 6731
Use arrow function inside the then
block to stay in the scope:
.then(response => {
this.setState({
data: response.data.main.temp
})
})
Upvotes: 6