Reputation: 81
I'm trying to track anchor tag (<a>
) clicks in React (i.e. send a POST
request to my server right before the navigation occurs).
My code currently looks like this:
<a
href="http://example.com"
onClick={() => axios.post('http://my-server.com', { value: 'Hello' })}
>
Click Me!
</a>
But the problem is that because the POST
request is asynchronous, the "href event" occurs before the request finish, so the request gets canceled.
So how can I perform an asynchronous event before the navigation occurs?
Upvotes: 1
Views: 2348
Reputation: 1249
Start by accepting a event into your on click handler. This will allow you to stop the navigation until the post has completed.
Axios returns a promise when you make a request. You need to wait for that to complete and then handle your navigation.
(event) => {
// stop the browser from navigating
event.preventDefault();
// save url so that you have the value after the event was disposed
const redirectUrl = event.target.href;
axios.post('http://my-server.com', { value: 'Hello' })
.then(response => {
// handle success
console.log(response);
})
.catch(error => {
// handle error
console.log(error);
})
.then(() => {
// always executed
// navigate logic here
console.log(redirectUrl);
});
}
Upvotes: 1
Reputation: 510
If you are looking for tracking anchor, you can use ping
attribute to do so. check this.
<a href="/stackoverflow" ping="/tracker/going-to-stackoverflow">click>
please note that this is not supported in all browsers.
Upvotes: 1