All files / web/src/lib/api example.ts

0% Statements 0/126
0% Branches 0/1
0% Functions 0/1
0% Lines 0/126

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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127                                                                                                                                                                                                                                                             
/**
 * Example API hooks using React Query
 *
 * This file demonstrates how to use React Query with the configured
 * QueryClient and apiUrl helper for making API requests.
 */

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '@/lib/queryClient'

// Example type for an API resource
interface User {
  id: string
  name: string
  email: string
}

/**
 * Example query hook - fetches a list of users
 */
export function useUsers() {
  return useQuery({
    queryKey: ['users'],
    queryFn: async () => {
      const response = await api('users')
      if (!response.ok) {
        throw new Error('Failed to fetch users')
      }
      return response.json() as Promise<User[]>
    },
  })
}

/**
 * Example query hook - fetches a single user by ID
 */
export function useUser(userId: string) {
  return useQuery({
    queryKey: ['users', userId],
    queryFn: async () => {
      const response = await api(`users/${userId}`)
      if (!response.ok) {
        throw new Error('Failed to fetch user')
      }
      return response.json() as Promise<User>
    },
    enabled: !!userId, // Only run query if userId is provided
  })
}

/**
 * Example mutation hook - creates a new user
 */
export function useCreateUser() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (newUser: Omit<User, 'id'>) => {
      const response = await api('users', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(newUser),
      })
      if (!response.ok) {
        throw new Error('Failed to create user')
      }
      return response.json() as Promise<User>
    },
    onSuccess: () => {
      // Invalidate and refetch users query after successful creation
      queryClient.invalidateQueries({ queryKey: ['users'] })
    },
  })
}

/**
 * Example mutation hook - updates a user
 */
export function useUpdateUser() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (user: User) => {
      const response = await api(`users/${user.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(user),
      })
      if (!response.ok) {
        throw new Error('Failed to update user')
      }
      return response.json() as Promise<User>
    },
    onSuccess: (updatedUser) => {
      // Invalidate both the list and the individual user query
      queryClient.invalidateQueries({ queryKey: ['users'] })
      queryClient.invalidateQueries({ queryKey: ['users', updatedUser.id] })
    },
  })
}

/**
 * Example mutation hook - deletes a user
 */
export function useDeleteUser() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (userId: string) => {
      const response = await api(`users/${userId}`, {
        method: 'DELETE',
      })
      if (!response.ok) {
        throw new Error('Failed to delete user')
      }
    },
    onSuccess: () => {
      // Invalidate users query after successful deletion
      queryClient.invalidateQueries({ queryKey: ['users'] })
    },
  })
}