import { useQuery, useQueryClient } from '@tanstack/react-query' import { useCallback } from 'react' import { resourceKeys } from './keys' import { get, handleError } from '@/data/fetchers' import type { ResponseError, UseCustomQueryOptions } from '@/types' export type ResourcesVariables = { projectRef?: string } export async function getResources({ projectRef }: ResourcesVariables, signal?: AbortSignal) { if (!projectRef) throw new Error('projectRef is required') // Use any of the API endpoints as the parameter here, TS will check if its valid - "branches" here is just an example const { data, error } = await get(`/v1/projects/{ref}/branches`, { params: { path: { ref: projectRef } }, signal, }) if (error) handleError(error) return data } export type ResourcesData = Awaited> export type ResourcesError = ResponseError export const useResourcesQuery = ( { projectRef }: ResourcesVariables, { enabled = true, ...options }: UseCustomQueryOptions = {} ) => useQuery({ queryKey: resourceKeys.list(projectRef), queryFn: ({ signal }) => getResources({ projectRef }, signal), enabled: enabled && typeof projectRef !== 'undefined', ...options, }) /** * useResourcesPrefetch is used for prefetching data. For example, starting a query loading before a page is navigated to. * Feel free to omit if not required * * @example * const prefetch = useResourcesPrefetch({ projectRef }) * * return ( * prefetch()}> * Start loading on hover * * ) */ export const useResourcesPrefetch = ({ projectRef }: ResourcesVariables) => { const client = useQueryClient() return useCallback(() => { if (projectRef) { client.prefetchQuery({ queryKey: resourceKeys.list(projectRef), queryFn: ({ signal }) => getResources({ projectRef }, signal), }) } }, [projectRef]) }