Reputation: 8990
In my React app I have a button, which on clicking I'm calling a function to make a API request, however I see Uncaught (in promise) Error
error.
I'm wondering whether I'm doing what I am in the correct way.
I've used useEffect
in the past when the page loads to call an API, but not sure how to do this on a button click.
So in the render I have:
<Fab onClick={approveIt}>Go</Fab>
Then that function - which sits within the function component itself:
const [success, setSuccess] = React.useState(false);
function approveIt() {
axios.post(api, {}).then(response => {
// Simplified - lets just get the response
console.log(response.status)
// And set some state
setSuccess(true);
});
}
Any help would be appreciated.
Thanks
Upvotes: 0
Views: 548
Reputation: 3274
There is probably an error in your axios call and you're not catching it. You can fix it this way:
axios.post(api, {})
.then(response => {
// Simplified - lets just get the response
console.log(response.status)
// And set some state
setSuccess(true);
})
.catch((error) => { console.log(error); })
Upvotes: 1
Reputation: 3855
Similar to a try, catch
statement, you have to add a .catch
to your axios.post
call in case an error occurs, in order to handle it. You could do something like this:
axios.post(api, {}).then(response => {
// Simplified - lets just get the response
console.log(response.status)
// And set some state
setSuccess(true);
})
.catch(err => {
console.log(err);
setSuccess(false);
});
Upvotes: 1