Skip to content

Commit

Permalink
docs: add example for navigation guards
Browse files Browse the repository at this point in the history
thanks to @lstar19
  • Loading branch information
posva committed Oct 9, 2019
1 parent 5c5b8ab commit e014630
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion docs/guide/advanced/navigation-guards.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,24 @@ Every guard function receives three arguments:

- **`next(error)`**: (2.4.0+) if the argument passed to `next` is an instance of `Error`, the navigation will be aborted and the error will be passed to callbacks registered via [`router.onError()`](../../api/#router-onerror).

**Make sure to always call the `next` function exactly one time in each navigation guard, otherwise the hook will never be resolved or produce errors.**
**Make sure that the `next` function is called exactly once in any given navigation guard. It can appear more than once, but only if the logical paths have no overlap, otherwise the hook will never be resolved or produce errors.** Here is an example of redirecting to user to `/login` if they are not authenticated:

```js
// BAD
router.beforeEach((to, from, next) => {
if (!isAuthenticated) next('/login')
// if the user is not authenticated, `next` is called twice
next()
})
```

```js
// GOOD
router.beforeEach((to, from, next) => {
if (!isAuthenticated) next('/login')
else next()
})
```

## Global Resolve Guards

Expand Down

2 comments on commit e014630

@laurieontech
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yay! Can I make one recommendation?
"Make sure that the next function is called exactly once in any given navigation guard."
Might work better as:
"Make sure that the next function is called exactly once in any given pass through the navigation guard."

@posva
Copy link
Member Author

@posva posva commented on e014630 Oct 9, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated!

Please sign in to comment.