T
TanStack•11mo ago
deep-jade

How can I use ensureQueryData in a component? - Help please 😂

I am using ensureQueryData like this in a custom hook:
export const useInitialDataEnsureQueryData = () => {
const [initialData, setInitialData] =
useState<FetchInitialData.Return | null>(null)
const queryClient = useQueryClient()

useEffect(() => {
async function ensureInitialData() {
const initialData = await queryClient.ensureQueryData({
queryKey: INITIAL_DATA_QUERY_KEY,
queryFn: () => fetchInitialData(),
})

setInitialData(initialData)
}

ensureInitialData()
}, [queryClient])


return initialData
}
export const useInitialDataEnsureQueryData = () => {
const [initialData, setInitialData] =
useState<FetchInitialData.Return | null>(null)
const queryClient = useQueryClient()

useEffect(() => {
async function ensureInitialData() {
const initialData = await queryClient.ensureQueryData({
queryKey: INITIAL_DATA_QUERY_KEY,
queryFn: () => fetchInitialData(),
})

setInitialData(initialData)
}

ensureInitialData()
}, [queryClient])


return initialData
}
I want to use the data in a component, that's why I am using a hook, but even tough the data is already in cache, a new fetch is done. Am I using it wrong?
2 Replies
deep-jade
deep-jadeOP•10mo ago
Is this meant to be used inside a component or is it more to be used inside a loader ?
yelping-magenta
yelping-magenta•10mo ago
ensureQueryData is for stuff like loaders yes. If you are in a component you can just use hooks like useQuery directly and then type narrow the states: https://tanstack.com/query/latest/docs/framework/react/typescript or useSuspenseQuery and handle the states at the Suspense and ErrorBoundary levels: https://tanstack.com/query/latest/docs/framework/react/guides/suspense
TypeScript | TanStack Query React Docs
React Query is now written in TypeScript to make sure the library and your projects are type-safe! Things to keep in mind: Types currently require using TypeScript v4.7 or greater Changes to types in...
Suspense | TanStack Query React Docs
React Query can also be used with React's Suspense for Data Fetching API's. For this, we have dedicated hooks: Additionally, you can use the useQuery().promise and React.use() (Experimental) When usin...

Did you find this page helpful?