I'm trying to make a get request from the server using React and Unirest and store the information that comes back inside a variable with setState
, but I always get the same error.
TypeError: Cannot read property 'getData' of undefined.
export default class ApartmentsRow extends React.Component {
constructor(props) {
super(props);
this.state = {
data:[]
};
}
componentDidMount(){
var req = unirest("GET", "https://realtor.p.rapidapi.com/properties/detail");
req.query({
"listing_id": "608763437",
"prop_status": "for_sale",
"property_id": "4599450556"
});
req.headers({
"x-rapidapi-host": "realtor.p.rapidapi.com",
"x-rapidapi-key": "34b0f19259mshde1372a9f2958e5p13e3cdjsnf2452cd81a81"
});
req.end(function (res) {
if (res.error) throw new Error(res.error);
console.log(res.body);
this.getData(res.body.listing)
});
}
getData = (allData) =>{
this.setState({
data:allData
})
}
because this
in your callback point to the callback
, not point to the class instance, use an arrow function like this
req.end(res => {
if (res.error) throw new Error(res.error);
this.setData(res.body.listing)
});
also, you should change getData
-> setData
setData = data => {
this.setState({ data})
}
or just remove the setData
then use setState
inside the callback
req.end(res => {
if (res.error) throw new Error(res.error);
this.setState({ data: res.body.listing });
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.