router
router copied to clipboard
Use commands.prevent()
Hi!,
How can I execute commands.prevent() in my action?
I don't see the method in commands object.
Thanks!
Confirmed. The documentation on custom route actions does not match the actual implementation. I am not sure which of the two is the intended behavior, but it's definitely a bug.
As a workaround you could try using the redirect command (return commands.redirect()) or using the prevent command inside the onBeforeEnter lifecycle callback in a route web component.
Thanks!!
Any timeline on updating the commands in the action object with a prevent method ?
Confirmed. The documentation on custom route actions does not match the actual implementation. I am not sure which of the two is the intended behavior, but it's definitely a bug.
As a workaround you could try using the
redirectcommand (return commands.redirect()) or using thepreventcommand inside theonBeforeEnterlifecycle callback in a route web component.
This throws an error in the console...
I don't know where I have found it, but this is how i use it:
onBeforeLeave(location, commands, router) {
if (this._unsavedChanges) {
const dialog = document.createElement('x-dialog');
dialog.title = 'Warning!';
dialog.template = html`Unsaved changes. Save changes first!`;
this.renderRoot.appendChild(dialog);
return commands.prevent()
}
}
Notice, that I check my navigation before leaving a component rather than before entering a new one. Hope it helps!
We also have the use case where we want to prevent routing when the user decides from a discard changes dialog. The Vaadin router doc/API is not very clear here, workarounds are needed and this becomes a bit fuzzy.
Actions are always executed, so when we prevent routing in an onBeforeLeave the action which might have side effects are already executed. Workarounds become very fuzzy and preventing router actions etc. makes it clear. We now show a dialog in a router action to prevent the action, remember the decision of the user and act on this on the onBeforeLeave with a comment.prevent(). But as mentioned, this becomes fuzzy.
Any plans to:
- Add the prevent method to the action commands?
- Fix/improve some documentation (best practice?) so it is clear how to implement such use cases. Should actions for example not have side effects and only resolve the components, but if so the components are still created when the action is prevented in an OnBeforeLeave?
Related:
- https://github.com/vaadin/router/issues/448
- https://github.com/vaadin/router/issues/325
- https://github.com/vaadin/router/issues/716
- https://github.com/vaadin/router/issues/354