-
Notifications
You must be signed in to change notification settings - Fork 454
Update useAwaitableNavigate to handle navigations between pages reliably #2889
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| --- | ||
| '@clerk/clerk-js': patch | ||
| '@clerk/nextjs': patch | ||
| --- | ||
|
|
||
| Make useAwaitableNavigate handle navigations between pages reliably |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@clerk/nextjs': patch | ||
| --- | ||
|
|
||
| Make useAwaitableNavigate handle navigations between pages reliably |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
56 changes: 36 additions & 20 deletions
56
packages/nextjs/src/app-router/client/useAwaitableNavigate.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,46 +1,62 @@ | ||
| 'use client'; | ||
|
|
||
| import { useRouter } from 'next/navigation'; | ||
| import { useEffect, useRef, useTransition } from 'react'; | ||
| import { usePathname, useRouter } from 'next/navigation'; | ||
| import { useCallback, useEffect, useTransition } from 'react'; | ||
|
|
||
| type NavigateFunction = ReturnType<typeof useRouter>['push']; | ||
| declare global { | ||
| interface Window { | ||
| __clerk_internal_navPromisesBuffer: Array<() => void> | undefined; | ||
| __clerk_internal_navFun: (to: string) => Promise<void>; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Creates an "awaitable" navigation function that will do its best effort to wait for Next.js to finish its route transition. | ||
| * | ||
| * This is accomplished by wrapping the call to `router.push` in `startTransition()`, which should rely on React to coordinate the pending state. We key off of | ||
| * `isPending` to flush the stored promises and ensure the navigates "resolve". | ||
| */ | ||
| export const useAwaitableNavigate = () => { | ||
| // eslint-disable-next-line @typescript-eslint/unbound-method | ||
| const { push } = useRouter(); | ||
| const pathname = usePathname(); | ||
| const [isPending, startTransition] = useTransition(); | ||
| const clerkNavRef = useRef<(...args: Parameters<NavigateFunction>) => Promise<void>>(); | ||
| const clerkNavPromiseBuffer = useRef<(() => void)[]>([]); | ||
|
|
||
| // Set the navigation function reference only once | ||
| if (!clerkNavRef.current) { | ||
| clerkNavRef.current = (to, opts) => { | ||
| if (typeof window !== 'undefined') { | ||
| window.__clerk_internal_navFun = to => { | ||
| return new Promise<void>(res => { | ||
| clerkNavPromiseBuffer.current.push(res); | ||
| if (!window.__clerk_internal_navPromisesBuffer) { | ||
| // We need to use window to store the reference to the buffer, | ||
| // as ClerkProvider might be unmounted and remounted during navigations | ||
| // If we use a ref, it will be reset when ClerkProvider is unmounted | ||
| window.__clerk_internal_navPromisesBuffer = []; | ||
| } | ||
| window.__clerk_internal_navPromisesBuffer.push(res); | ||
| startTransition(() => { | ||
| push(to, opts); | ||
| push(to); | ||
| }); | ||
| }); | ||
| }; | ||
| } | ||
|
|
||
| // Handle flushing the promise buffer when pending is false. If pending is false and there are promises in the buffer we should be able to safely flush them. | ||
| const flushPromises = () => { | ||
| window.__clerk_internal_navPromisesBuffer?.forEach(resolve => resolve()); | ||
| window.__clerk_internal_navPromisesBuffer = []; | ||
| }; | ||
|
|
||
| // Flush any pending promises on mount/unmount | ||
| useEffect(() => { | ||
| if (isPending) { | ||
| return; | ||
| } | ||
| flushPromises(); | ||
| return flushPromises; | ||
| }, []); | ||
|
|
||
| if (clerkNavPromiseBuffer?.current?.length) { | ||
| clerkNavPromiseBuffer.current.forEach(resolve => resolve()); | ||
| // Handle flushing the promise buffer when a navigation happens | ||
| useEffect(() => { | ||
| if (!isPending) { | ||
| flushPromises(); | ||
| } | ||
| clerkNavPromiseBuffer.current = []; | ||
| }, [isPending]); | ||
| }, [pathname, isPending]); | ||
|
|
||
| return clerkNavRef.current; | ||
| return useCallback((to: string) => { | ||
| return window.__clerk_internal_navFun(to); | ||
| }, []); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I believe removing the transition here will re-introduce the original issue, which is that state updates were happening during the router transition, or that the setActive call was not completing at all because of the navigation triggered by
onBeforeSetActive.Is there a way we can retain the use of the transition while keeping the buffer on the window?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We'll most likely keep using the transition API - this is removed temporarily so I can cut a snapshot version for testing
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Regarding this one, I never managed to reproduce a failed setActive because of us not listening to
isPendingI think the issue was caused by the components being unmounted during navigation but I do agree that keep using transition state is the way to go here