Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React cannot set property of undefined

Tags:

reactjs

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?

like image 677
MickeyTheMouse Avatar asked Nov 29 '25 19:11

MickeyTheMouse


2 Answers

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);
    });
  }
like image 171
Liam Avatar answered Dec 01 '25 07:12

Liam


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)=> {
     ...
    });
like image 25
Rohith Murali Avatar answered Dec 01 '25 08:12

Rohith Murali