I'm new to react and I'm trying to pull and display data from randomuserapi. I've made the api call but when I run my app, I get the error below:
./src/App.js
Line 45: 'getData' is not defined no-undef
Here's my code below: The getData() method is where I make the api call. That method is now called in ComponentDidMount.
I also binded getData() to my constructor but I still get the error above.
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
people: []
}
this.getData = this.getData.bind(this);
}
getData() {
const promise = fetch('https://randomuser.me/api/?results=20')
.then(response => {
if (response.status >= 400) {
throw `Response Invalid ( ${response.status} )`;
return;
}
return response.json();
})
.then(({results}) => {
return results;
})
.catch(error => {
console.log(error);
});
return promise;
}
ComponenDidMount() {
getData()
.then(data => {
this.setState({
people: data
});
});
}
render() {
return (
<div>
<p>{this.state.people.results[0].gender}</p>
</div>
);
}
}
export default App;
I'm also using create-react-app from Github. Please some assistance will be helpful.
Thanks!
When you reference defined methods you need to say this
so:
componenDidMount() {
this.getData()
.then(data => {
this.setState({
people: data
});
});
}
Try adding this.
when calling your functions. this.getData()
inside componentDidMount
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.