From d60d36c49bbbd308618926ff0131890bfed2cdff Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Thu, 6 Jul 2023 18:31:35 +0200 Subject: [PATCH] fix: allow removing guards within the guard --- packages/router/__tests__/guards/afterEach.spec.ts | 12 ++++++++++++ packages/router/src/router.ts | 6 +++--- packages/router/src/utils/callbacks.ts | 2 +- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/packages/router/__tests__/guards/afterEach.spec.ts b/packages/router/__tests__/guards/afterEach.spec.ts index 01a9d44f..d4200486 100644 --- a/packages/router/__tests__/guards/afterEach.spec.ts +++ b/packages/router/__tests__/guards/afterEach.spec.ts @@ -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) + }) }) diff --git a/packages/router/src/router.ts b/packages/router/src/router.ts index dbd426f3..43eaecfd 100644 --- a/packages/router/src/router.ts +++ b/packages/router/src/router.ts @@ -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))) } /** diff --git a/packages/router/src/utils/callbacks.ts b/packages/router/src/utils/callbacks.ts index 6f9f5aab..441aba81 100644 --- a/packages/router/src/utils/callbacks.ts +++ b/packages/router/src/utils/callbacks.ts @@ -18,7 +18,7 @@ export function useCallbacks() { return { add, - list: () => handlers, + list: () => handlers.slice(), reset, } } -- 2.47.2