@@ -432,14 +432,14 @@ have a working Next.js app with Convex. If not follow the
432
432
433
433
``` tsx title="components/ConvexClientProvider.tsx"
434
434
' use client' ;
435
-
436
- import { ReactNode , useCallback , useRef } from ' react' ;
435
+
436
+ import { ReactNode , useCallback } from ' react' ;
437
437
import { ConvexReactClient } from ' convex/react' ;
438
438
import { ConvexProviderWithAuth } from ' convex/react' ;
439
439
import { AuthKitProvider , useAuth , useAccessToken } from ' @workos-inc/authkit-nextjs/components' ;
440
-
440
+
441
441
const convex = new ConvexReactClient (process .env .NEXT_PUBLIC_CONVEX_URL ! );
442
-
442
+
443
443
export function ConvexClientProvider({ children }: { children: ReactNode }) {
444
444
return (
445
445
<AuthKitProvider >
@@ -449,27 +449,35 @@ have a working Next.js app with Convex. If not follow the
449
449
</AuthKitProvider >
450
450
);
451
451
}
452
-
452
+
453
453
function useAuthFromAuthKit() {
454
454
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
+
471
479
return {
472
- isLoading: loading ,
480
+ isLoading ,
473
481
isAuthenticated: authenticated ,
474
482
fetchAccessToken ,
475
483
};
0 commit comments