All files / src/lib useCheckStatus.ts

0% Statements 0/12
0% Branches 0/8
0% Functions 0/3
0% Lines 0/10

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                                                                                               
import { UseQueryOptions, useQuery } from '@tanstack/react-query'
import { ApiError } from 'next/dist/server/api-utils'
 
import { CheckStatusApiRequestQuery, CheckStatusApiResponse } from './types'
 
export const fetchCheckStatus = async (
  checkStatusApiRequestQuery: CheckStatusApiRequestQuery,
  init?: RequestInit,
): Promise<CheckStatusApiResponse | null> => {
  const query = new URLSearchParams({
    ...checkStatusApiRequestQuery,
  }).toString()
  const response = await fetch('/api/check-status?' + query, init)
  if (response.ok) return response.json()
  if (response.status === 404) return null
  throw new ApiError(response.status, response.statusText)
}
 
export const useCheckStatus = (
  checkStatusApiRequestQuery: CheckStatusApiRequestQuery,
  queryOptions?: Omit<
    UseQueryOptions<
      CheckStatusApiResponse | null,
      ApiError,
      CheckStatusApiResponse | null
    >,
    'queryKey' | 'queryFn'
  >,
) => {
  const query = useQuery<
    CheckStatusApiResponse | null,
    ApiError,
    CheckStatusApiResponse | null
  >({
    ...(queryOptions ?? {}),
    queryKey: ['ps:api:check-status', checkStatusApiRequestQuery],
    queryFn: ({ signal }) =>
      fetchCheckStatus(checkStatusApiRequestQuery, { signal }),
  })
 
  // fix isPending with disabled: false
  // see: https://github.com/TanStack/query/issues/3584#issuecomment-1256986636
  return {
    ...query,
    isPending: query.isPending && query.fetchStatus !== 'idle',
  }
}