1

I have two custom hooks for using useQuery.

The second hook depends on the result of the first

While the first hook is being executed its data is undefined

interface Props {
  id: number
  enabled: boolean | undefined
}

export const getFooQuery = (props: Props) => {
  const { id, enabled } = props

  return {
    queryKey: ['foo', id],
    queryFn: () => fetchFoo({ id }),
    staleTime: 10000,
    enabled
  }
}

export const useGetFoo= ({ id, enabled }: Props) => {
  const queryResult = useQuery(getFooQuery({ id, enabled }))

  return queryResult
}


export const App = () => {
  const {data: dataBar} = useGetBar()
  const {data: dataFoo} = useGetFoo({id: dataBar?.id, enabled: dataBar?.id})
                                       //^ number | null | undefined 

  //...
}

i have no idea. mb change type id to number | null | undefined, but then how to check it correctly

qvazi
  • 53
  • 4

1 Answers1

0

There aren't really good ways to make enabled typesafe. My recommended solution is to widen the type to number | null | undefined of your custom, and then check for this invariant in the queryFn:

type Props = {
  id: number | null | undefined;
  enabled: boolean
}

export const getFooQuery = (props: Props) => {
  const { id, enabled } = props

  return {
    queryKey: ['foo', id],
    queryFn: () => {
      if (!id) {
        return Promise.reject(new Error("no id provided"))
      }
      return fetchFoo({ id }),
    },
    staleTime: 10000,
    enabled
  }
}

see: https://tkdodo.eu/blog/react-query-and-type-script#type-safety-with-the-enabled-option

TkDodo
  • 20,449
  • 3
  • 50
  • 65