]> git.ipfire.org Git - thirdparty/vuejs/router.git/commitdiff
fix: allow removing guards within the guard
authorEduardo San Martin Morote <posva13@gmail.com>
Thu, 6 Jul 2023 16:31:35 +0000 (18:31 +0200)
committerEduardo San Martin Morote <posva13@gmail.com>
Thu, 6 Jul 2023 16:31:35 +0000 (18:31 +0200)
packages/router/__tests__/guards/afterEach.spec.ts
packages/router/src/router.ts
packages/router/src/utils/callbacks.ts

index 01a9d44f42064a6f1618faa768e1b77d4c177718..d4200486030e7363906c576845e1f89fd80c7ef8 100644 (file)
@@ -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)
+  })
 })
index dbd426f32351b4d467d58c979ea0f10f0cf08921..43eaecfddf458216df787ddd626c17a9178fe0e4 100644 (file)
@@ -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)))
   }
 
   /**
index 6f9f5aab66cabafc6f92c215f70f3377ead38bc5..441aba816088d73ca45ac8985ccfd2a03f1a4121 100644 (file)
@@ -18,7 +18,7 @@ export function useCallbacks<T>() {
 
   return {
     add,
-    list: () => handlers,
+    list: () => handlers.slice(),
     reset,
   }
 }