Uttam Tarsariya
Uttam Tarsariya

Reputation: 11

How to fix "_this2.setState is not a function"

Error while calling API and get list than a set that lists into the list from state. but setState() is not work properly and warning is

_this2.setState is not a function

callGithubApi(){
    axios.get("https://facebook.github.io/react-native/movies.json")
        .then(function(response)
        {
            console.log(JSON.stringify(response.data.movies))
            this.setState({   // problem is here
                list: response.data.movies,
                show: false
            })
        })
        .catch(error => 
        {
            this.setState({ errors : error, show: false })
        });
}

Upvotes: 1

Views: 85

Answers (3)

Phoenix
Phoenix

Reputation: 36

Use ES6's arrow function for that function and the function in then()

callGithubApi = () => {
    axios.get("https://facebook.github.io/react-native/movies.json")
      .then((response) =>
      {
           console.log(JSON.stringify(response.data.movies))
           this.setState({
             list: response.data.movies,
             show: false
         })
       })
      .catch(error => {
        this.setState({ errors : error, show: false })
      });
  }

Upvotes: 0

Shashin Bhayani
Shashin Bhayani

Reputation: 1578

use ES6's arrow function:

callGithubApi = () => {
    axios.get("https://facebook.github.io/react-native/movies.json")
      .then(function(response)
      {
           console.log(JSON.stringify(response.data.movies))
           this.setState({   // proble is here
           list: response.data.movies,
           show: false
         })
       })
      .catch(error => {
        this.setState({ errors : error, show: false })
      });
  }

or else you have to bind this function in contructor:

this.callGithubApi = this.callGithubApi.bind(this)

Upvotes: 3

Adarsh Gowda K R
Adarsh Gowda K R

Reputation: 951

Use Fat arrow function to fix this context issue.

callGithubApi(){
   axios.get("https://facebook.github.io/react-native/movies.json")
    .then((response) =>
    {
        console.log(JSON.stringify(response.data.movies))
        this.setState({   // problem is here
            list: response.data.movies,
            show: false
        })
    })
    .catch(error => 
    {
        this.setState({ errors : error, show: false })
    });
 }

Upvotes: 0

Related Questions