Last active
February 14, 2025 14:11
-
-
Save karol-majewski/8043e7bae328c189353932156f48f329 to your computer and use it in GitHub Desktop.
Accessing Privy users with Suspense
This file contains 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
import { use } from 'react'; | |
import { usePrivy, User } from '@privy-io/react-auth'; | |
const RETRY_INTERVAL = 50; // ms | |
// Move promise creation outside the component | |
let authPromise: Promise<User> | null = null; | |
function createAuthPromise(ready: boolean, authenticated: boolean, user: User | null) { | |
return new Promise<User>((resolve, reject) => { | |
function checkAuth() { | |
if (!ready) { | |
setTimeout(checkAuth, RETRY_INTERVAL); | |
return; | |
} | |
if (authenticated && user) { | |
resolve(user); | |
} else { | |
reject(new Error('User not authenticated')); | |
} | |
} | |
checkAuth(); | |
}); | |
} | |
export function usePrivyUser() { | |
const { ready, authenticated, user } = usePrivy(); | |
// Only create the promise once | |
if (!authPromise) { | |
authPromise = createAuthPromise(ready, authenticated, user); | |
} | |
return use(authPromise); | |
} |
This file contains 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
import { use } from 'react'; | |
import { usePrivy, User } from '@privy-io/react-auth'; | |
const cache = new Map<string, Promise<User>>(); | |
const CACHE_KEY = "privy-auth-state"; | |
const RETRY_INTERVAL = 50; // ms | |
export function usePrivyUser() { | |
const { ready, authenticated, user } = usePrivy(); | |
// If we don't have a cached promise, create one | |
if (!cache.has(CACHE_KEY)) { | |
const promise = new Promise<User>((resolve, reject) => { | |
// Inner function to handle the retry logic | |
function checkAuth() { | |
if (!ready) { | |
// If not ready, schedule another check | |
setTimeout(checkAuth, RETRY_INTERVAL); | |
return; | |
} | |
// Once ready, resolve or reject based on auth state | |
if (authenticated && user) { | |
resolve(user); | |
} else { | |
reject(new Error("User not authenticated")); | |
} | |
} | |
// Start the checking process | |
checkAuth(); | |
}); | |
cache.set(CACHE_KEY, promise); | |
} | |
// Use the cached promise | |
return use(cache.get(CACHE_KEY)!); | |
} | |
// Optional: Add a function to clear the cache if needed | |
export function clearPrivyCache() { | |
cache.clear(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment