2

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

BarbeBleue
  • 45
  • 6

2 Answers2

4

This is lexical scope issue. Use arrow function.

.then((response) => {
    this.setState({ res: response });
})
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
2

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:

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);
         });
 }
Raeesaa
  • 3,267
  • 2
  • 22
  • 44