Functions inside componentDidMount are undefined
There is some fundamental misunderstanding here, you can still call the functions inside componentDidMount
, however you should not define them inside it.
Simply define the functions outside componentDidMount
and this will solve your problems, here is a short example
componentDidMount() {
this.fetchUser(this.state.username);
}
function fetchUser(username) {
let url = `https://api.github.com/users/${username}`;
this.fetchApi(url);
};
function fetchApi(url) {
fetch(url)
.then((res) => res.json())
.... some data that is being fetched ....
});
};
Its a simple matter of scope:
function outer(){
function inner(){
}
}
inner(); // error does not exist
As birdmars suggested you should call this.fetchUser()
inside component did mount. but declare the function outside!
class App extends Component {
render() {
return (
<div>
<SearchBox onSubmit={this.fetchUser}/>
<Card data={this.state} />
<BaseMap center={this.state.address}/>
</div>
);
}
fetchUser(username) {
let url = `https://api.github.com/users/${username}`;
this.fetchApi(url);
};
fetchApi(url) {
fetch(url)
.then((res) => res.json())
.... some data that is being fetched ....
});
};
componentDidMount() {
let url = username; //frome somewhere, most probably props then use props Changed function instead!
var user = his.fetchUser(url)
this.setState(() => {user: user});
}
}
export default App;