Skip to content

Commit

Permalink
fix: allow removing guards within the guard
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Jul 6, 2023
1 parent 27ba8dd commit d60d36c
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
12 changes: 12 additions & 0 deletions packages/router/__tests__/guards/afterEach.spec.ts
Expand Up @@ -65,4 +65,16 @@ describe('router.afterEach', () => {
)
expect(spy).toHaveBeenCalledTimes(2)
})

it('removing an afterEach guard within one does not affect others', async () => {
const spy1 = jest.fn()
const spy2 = jest.fn()
const router = createRouter({ routes })
router.afterEach(spy1)
const remove = router.afterEach(spy2)
spy1.mockImplementationOnce(remove)
await router.push('/foo')
expect(spy1).toHaveBeenCalledTimes(1)
expect(spy2).toHaveBeenCalledTimes(1)
})
})
6 changes: 3 additions & 3 deletions packages/router/src/router.ts
Expand Up @@ -906,9 +906,9 @@ export function createRouter(options: RouterOptions): Router {
): void {
// navigation is confirmed, call afterGuards
// TODO: wrap with error handlers
for (const guard of afterGuards.list()) {
runWithContext(() => guard(to, from, failure))
}
afterGuards
.list()
.forEach(guard => runWithContext(() => guard(to, from, failure)))
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/router/src/utils/callbacks.ts
Expand Up @@ -18,7 +18,7 @@ export function useCallbacks<T>() {

return {
add,
list: () => handlers,
list: () => handlers.slice(),
reset,
}
}

0 comments on commit d60d36c

Please sign in to comment.