All files / web/src/hooks useUserId.ts

58.53% Statements 24/41
100% Branches 0/0
0% Functions 0/3
58.53% Lines 24/41

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 421x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                     1x 1x 1x 1x 1x 1x 1x 1x                
'use client'
 
import { useQuery } from '@tanstack/react-query'
import { api } from '@/lib/queryClient'
 
/**
 * Query key for user identity
 */
export const identityKeys = {
  all: ['identity'] as const,
  id: () => [...identityKeys.all, 'id'] as const,
}
 
/**
 * Fetch the current user's stable database user.id
 */
async function fetchUserId(): Promise<string | null> {
  try {
    const res = await api('identity')
    if (!res.ok) return null
    const data = await res.json()
    return data.userId
  } catch {
    return null
  }
}
 
/**
 * Hook: Get the current user's stable database user.id
 *
 * Returns the database user.id for both authenticated users and guests.
 * Returns null if no valid session exists.
 */
export function useUserId() {
  return useQuery({
    queryKey: identityKeys.id(),
    queryFn: fetchUserId,
    staleTime: 5 * 60 * 1000, // 5 minutes
    retry: false,
  })
}