@@ -432,14 +432,14 @@ have a working Next.js app with Convex. If not follow the
432432
433433 ``` tsx title="components/ConvexClientProvider.tsx"
434434 ' use client' ;
435-
436- import { ReactNode , useCallback , useRef } from ' react' ;
435+
436+ import { ReactNode , useCallback } from ' react' ;
437437 import { ConvexReactClient } from ' convex/react' ;
438438 import { ConvexProviderWithAuth } from ' convex/react' ;
439439 import { AuthKitProvider , useAuth , useAccessToken } from ' @workos-inc/authkit-nextjs/components' ;
440-
440+
441441 const convex = new ConvexReactClient (process .env .NEXT_PUBLIC_CONVEX_URL ! );
442-
442+
443443 export function ConvexClientProvider({ children }: { children: ReactNode }) {
444444 return (
445445 <AuthKitProvider >
@@ -449,27 +449,35 @@ have a working Next.js app with Convex. If not follow the
449449 </AuthKitProvider >
450450 );
451451 }
452-
452+
453453 function useAuthFromAuthKit() {
454454 const { user, loading : isLoading } = useAuth ();
455- const { accessToken, loading : tokenLoading, error : tokenError } = useAccessToken ();
456- const loading = (isLoading ?? false ) || (tokenLoading ?? false );
457- const authenticated = !! user && !! accessToken && ! loading ;
458-
459- const stableAccessToken = useRef <string | null >(null );
460- if (accessToken && ! tokenError ) {
461- stableAccessToken .current = accessToken ;
462- }
463-
464- const fetchAccessToken = useCallback (async () => {
465- if (stableAccessToken .current && ! tokenError ) {
466- return stableAccessToken .current ;
467- }
468- return null ;
469- }, [tokenError ]);
470-
455+ const { accessToken, getAccessToken, refresh } = useAccessToken ();
456+
457+ const authenticated = !! user && !! accessToken ;
458+
459+ const fetchAccessToken = useCallback (
460+ async ({ forceRefreshToken }: { forceRefreshToken? : boolean } = {}): Promise <string | null > => {
461+ if (! user ) {
462+ return null ;
463+ }
464+
465+ try {
466+ if (forceRefreshToken ) {
467+ return (await refresh ()) ?? null ;
468+ }
469+
470+ return (await getAccessToken ()) ?? null ;
471+ } catch (error ) {
472+ console .error (' Failed to get access token:' , error );
473+ return null ;
474+ }
475+ },
476+ [user , refresh , getAccessToken ],
477+ );
478+
471479 return {
472- isLoading: loading ,
480+ isLoading ,
473481 isAuthenticated: authenticated ,
474482 fetchAccessToken ,
475483 };
0 commit comments