I have the following function within a React component which is run when a link is clicked:
onClick(e, { name }) {
e.stopPropagation();
const doIt = await checkSomething();
if (doIt) {
e.preventDefault();
doSomethingElse();
}
}
Problem is that by the time e.preventDefault()
is reached the synthetic event is recycled. So, how do I tell the browser not to follow the link if it is clicked, when some logic is needed to calculate this decision and before the synthetic event is recycled?
One way to handle this would be to use
preventDefault
and when the action is complete and you need to route, call the Routing logic yourself usinghistory.push()
Check this answer on how to Programmatically navigate with React-router
I'm just throwing an idea here.
If you can't or don't want to do the URL redirect programmatically, then there is an alternative.
You can nest a function (currying) and invoke the second function only after you finish your logic.
Note that this will require you to write your nested function as an IIFE.
Here is a small proof of concept using JavaScript (open console):
Example with react:
To use
preventDefault
on an event, you need to do it before the callback function returns. This is not something you can do after the completion of an asynchronous task.If you look at MDN Event.preventDefault Notes, you'll notice it says you have to call it somewhere in the event flow.
You can also refer to this SO question: event.preventDefault in async functions . In the top answer, you'll see mention of the use of
await
and how theevent.preventDefault()
needs to occur before the firstawait
statement. This holds true for using promises, or any asynchronous action.As an aside:
Here is the SyntheticEvent documentation.
Have you tried using promises and .then():
You should be able to control preventDefault();