Reputation: 53
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!
Upvotes: 2
Views: 13202
Reputation: 51
Try adding this.
when calling your functions.
this.getData()
inside componentDidMount
Upvotes: 4
Reputation: 5770
When you reference defined methods you need to say this
so:
componenDidMount() {
this.getData()
.then(data => {
this.setState({
people: data
});
});
}
Upvotes: 5