0

I am getting the data I need from the response, but I get a TypeError and I don't understand why? What do I need to do to fix this?

  componentDidMount() {
    const getData = axios.get("https://web-code-test-xxx-games-prd.appspot.com/cards.json")
      .then(function(response) {
        const easyResponse = response.data.levels[0]['difficulty']
        const easyCards = response.data.levels[0]['cards']
        this.setState({ easy: easyResponse})
        this.setState({easyCards: easyCards})

       })
      .catch(function(error) {
        console.log(error);
      });

}

Kevin T.
  • 668
  • 3
  • 12
  • 29

1 Answers1

0

The TypeError was not in the get request, it was coming from the Promise object that was returned. Axios is an asynchronous action and the 'this' is lost/ different inside Axios thus the 'this' in this.setState was not being read properly. By switching to an arrow function the 'this' is no longer the axios object but the context object, the react component. Here is another answer.

Kevin T.
  • 668
  • 3
  • 12
  • 29