Search code examples
javascriptreactjsfunctionreact-nativesetstate

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


Solution

  • This is lexical scope issue. Use arrow function.

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