why tanstack-query data type is T & ({} | null)

76 views Asked by At

sorry for bad english

I want to make custom search hook using tanstack query v5.

import { useState } from "react"

import { useQuery } from "@tanstack/react-query"

type callback<T> = () => Promise<T>

export const useSearchList = <T>(initialValue = "", queryFn: callback<T>) => {
 const [keyword, setKeyword] = useState(initialValue)

 const onSearch = (value: string) => {
   if (value.length === 0) {
     return
   }
   setKeyword(value.trim())
 }

 const { data } = useQuery({
   queryKey: ["search", keyword],
   queryFn,
   enabled: keyword.length > 0,
 })

 if (data === undefined) {
   throw new Error("test")
 }

 return { data, onSearch }
}

I want to make data type only 'T', so I throw Error if data is undefined. but returned data type is T & ({} | null)

I tried placeholderData , but it causes type Error. is any good idea to avoid data type undefined? and I want to know this hook is available

1

There are 1 answers

0
ouuan On BEST ANSWER

Because the data could be still pending. You need to set the initialData option to avoid it being undefined.

References: