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.