Reputation: 2692
I'm using Axios to do make an API call a (get request) inside the life cycle method componentDidMount
.
It's working fine, I'm getting my result and saving the data using setState.
componentDidMount(){
axios.get("https://myAPI/v1/myAPI-Endpoint?myAPI-Key=12345678910abcdef")
.catch(error => console.log('Error', error))
.then(
(response) => {
let data = response.data;
this.setState({
myFetchedData: data
});
},
)
}
The question:
Where should I do that 2nd API call now, I assume that I cannot do it in componentDidMount
since the component is already mounted?
So what is the best practice here? Where should I do an API call that is triggered by a user action?
Upvotes: 0
Views: 91
Reputation: 142
Your autocomplete component is likely to have some sort of event that fires when a selection was made (something like 'onChange', 'onSelect', etc, this depends on the component).
You could then do something like this (in your render function):
<AutoComplete
onSelect={this.handleAutoCompleteSelect}
…
/>
and then, inside the component class:
…
handleAutoCompleteSelect (value) {
axios.get(apiEndpont, { value }) // Exact request depends on your api implementation
.catch(…)
.then(function (res) {
// Process request result here
})
}
Upvotes: 1