Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.setState() is not a function -> when trying to save response on state

I'm trying to save the response of a get request onto a property on state. Here's my code:

import React, { Component } from 'react';
import {render} from 'react-dom';

import './App.css';
import Card from './Card.js';
import SearchBar from "./SearchBar.js"
import star from './images/star.svg';
import wars from './images/wars.svg';
import $ from './../node_modules/jquery';

class App extends Component {

constructor(props){
  super(props);
  this.state = {
    gets: []      //THIS IS WHERE THE RESPONSE ARR SHOULD BE SAVED 
  }
}

////////////////////////////
//     GET REQUEST        //
////////////////////////////

getTheApi(){
$.get('http://localhost:3008/people', function(cool){
    console.log(cool) //<-- the response is correct (array of objs)
    this.setState({gets:cool}).bind(this)   //have tried w/ w/out .bind(this)
  })
}

render() {

console.log(this.state.gets); //shows as undefined

    return (
      <div className='content'>
        <div className='logo'>
          <img src={star} alt="star-logo" />
          <span className='interview-text'>The Interview</span>
          <img src={wars} alt="wars-logo" />
          <span>WHATTTTTT</span>
        </div>
        <SearchBar />
        <Card />
      </div>
    );
  }
}

render(<App/>, document.getElementById('app'));

I've tried multiple ways to get this to work, but no dice. I've tried this.setState({gets:cool}) with and without bind. I've console logged the variable cool before this.setState and I am getting the correct array of objects. But when I then try to save my response to state it says

Type Error: this.setState() is not a function.

I've also tried invoking getTheAPI() inside of render, thinking state wasn't being updated because the function was never being run, but the errors persisted.

I just can't figure out why the response is defined in the function, but not out of the function, and why it's saying this.setState() is not a function.

Help me Obi Wan Kenobi, you're my only hope.

like image 425
atrev Avatar asked Oct 17 '25 18:10

atrev


1 Answers

The this inside the success callback function does not refer to the this of the Component. Since you are using ES6, you can use arrow function which provide lexical scoping.

Example:

 getTheApi = () => {
     $.get('http://localhost:3008/people', (cool) => {
        this.setState({gets:cool})
     })
 }
like image 137
Swapnil Avatar answered Oct 20 '25 09:10

Swapnil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!