I'm making a get request using axios. I know for a fact that when I make a get request, I get the correct data.
I have an array (allQuotes) in my constructor. However, when I try to reference it in componentDidMount, it's undefined.
class App extends Component {
constructor() {
super();
this.allQuotes = [];
}
componentDidMount() {
axios.get("http://getquote.herokuapp.com/get")
.then(function (response) {
this.allQuotes = response.data;
console.log(response.data);
this.getNewQuote();
})
.catch(function (error) {
console.log("Error: ", error);
//console.dir(error);
});
}
}
Upon running this, the console says "Cannot set property 'allQuotes' of undefined".
Why is this undefined?
It's better if you put allQuotes in state then you use setState
class App extends Component {
constructor() {
super();
this.state = {
allQuotes: [],
}
}
componentDidMount() {
axios.get("http://getquote.herokuapp.com/get")
.then(function (response) {
this.setState({ allQuotes: response.data })
console.log(response.data);
this.getNewQuote();
})
.catch(function (error) {
console.log("Error: ", error);
//console.dir(error);
});
}
You can use arrow functions to fix this. The problem is because if its another function, this refers to the function, and arrow function doesnt have one, instead it has the this of its referer.
axios.get("http://getquote.herokuapp.com/get")
.then((response)=>{
...
})
.catch( (error)=> {
...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With