Skip to content

Commit d60d36c

Browse files
committed
fix: allow removing guards within the guard
1 parent 27ba8dd commit d60d36c

File tree

3 files changed

+16
-4
lines changed

3 files changed

+16
-4
lines changed

packages/router/__tests__/guards/afterEach.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,4 +65,16 @@ describe('router.afterEach', () => {
6565
)
6666
expect(spy).toHaveBeenCalledTimes(2)
6767
})
68+
69+
it('removing an afterEach guard within one does not affect others', async () => {
70+
const spy1 = jest.fn()
71+
const spy2 = jest.fn()
72+
const router = createRouter({ routes })
73+
router.afterEach(spy1)
74+
const remove = router.afterEach(spy2)
75+
spy1.mockImplementationOnce(remove)
76+
await router.push('/foo')
77+
expect(spy1).toHaveBeenCalledTimes(1)
78+
expect(spy2).toHaveBeenCalledTimes(1)
79+
})
6880
})

packages/router/src/router.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -906,9 +906,9 @@ export function createRouter(options: RouterOptions): Router {
906906
): void {
907907
// navigation is confirmed, call afterGuards
908908
// TODO: wrap with error handlers
909-
for (const guard of afterGuards.list()) {
910-
runWithContext(() => guard(to, from, failure))
911-
}
909+
afterGuards
910+
.list()
911+
.forEach(guard => runWithContext(() => guard(to, from, failure)))
912912
}
913913

914914
/**

packages/router/src/utils/callbacks.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ export function useCallbacks<T>() {
1818

1919
return {
2020
add,
21-
list: () => handlers,
21+
list: () => handlers.slice(),
2222
reset,
2323
}
2424
}

0 commit comments

Comments
 (0)