0

i have a function component file called postdata.js, which i am using inside of app.js. Inside the postdata, i am having a function which fetched value from API(which in working). But when i use this.setState in the invoked postdata function and assign it to the API result value, i throws an error:

Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined

postdata.js:

export function Postdata(url=''){

  return fetch(url).then(
     function(response){

         console.log("response.json()::",response)
         return response.json();
    })

}

app.js:

import React, { Component } from 'react';
import logo from './logo.svg';
import {Table} from 'reactstrap';
import './App.css';
import {Postdata} from './postdata';

class App extends React.Component {

  constructor(props){

    super(props);
      this.state = {
          hits: 'sduhyh',
          result_:[]
      }
 //this.Postdata = this.Postdata.bind(this)
    }

    componentDidMount() {}

  postdata_fire(){

    Postdata('http://localhost:3000/places').then(function(result){
      console.log("result::",result);
      this.setState({result:'sdujoij'})

})


    this.setState({hits:'yahittsss'})
    console.log("hits:::",this.state.hits); 
  }

  render() {
    return (
      <div className="App container">



   <div>{this.state.hits}</div>

        <button onClick={this.postdata_fire.bind(this)}></button>
      </div>
    );
  }
}

export default App;

Please help.

user3450590
  • 341
  • 2
  • 14
  • Possible duplicate of [I have one this.state and i need pass in my componentDidMount with setState, how use bind(this) in setState?](https://stackoverflow.com/questions/54615829/i-have-one-this-state-and-i-need-pass-in-my-componentdidmount-with-setstate-how) – keul Mar 04 '19 at 11:30

2 Answers2

1

You'll need to refactor postdata_fire like this:

postdata_fire() {
 Postdata('http://localhost:3000/places').then(result => {
   console.log("result:: %j",result);
   this.setState({result_: result});
 });
 ...
}

and Postdata too:

export const Postdata = (url='') => {
  return fetch(url).then(response => {
    console.log("response.json()::",response)
    return response.json();
  });
}

0

your promise response does not share the this scope so use arrow function inside the then response...


  postdata_fire(){
    Postdata('http://localhost:3000/places').then((result) =>{
      console.log("result::",result);
      this.setState({result:'sdujoij'})
    })

    this.setState({hits:'yahittsss'})
    console.log("hits:::",this.state.hits); 
  }
sathish kumar
  • 1,477
  • 1
  • 11
  • 18