React Native setState not a function

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

Answers:

Answer

This is lexical scope issue. Use arrow function.

.then((response) => {
    this.setState({ res: response });
})
Answer

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);
         });
 }

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.