T
TanStack3y ago
noble-gold

How to use react-intersection-observer with useQuery?

I don't want to fire useQuery until the container is in view. Here is the code I have written:
import {useInView} from "react-intersection-observer";
//other code
const {ref: inViewRef, inView} = useInView({triggerOnce: true});

const {data, refetch, isLoading, isError} = useQuery(
[RQConstants.GET_PRIVATE_FILE_BYTES, fileUrl],
async () => {
const {data} = await axios.get(URN_MEDIA + "/file?uri=" + fileUrl);
return data;
},
{
refetchOnMount: false,
refetchOnWindowFocus: false,
staleTime: "Infinity",
cacheTime: "Infinity",
enabled: inView,
}
);
import {useInView} from "react-intersection-observer";
//other code
const {ref: inViewRef, inView} = useInView({triggerOnce: true});

const {data, refetch, isLoading, isError} = useQuery(
[RQConstants.GET_PRIVATE_FILE_BYTES, fileUrl],
async () => {
const {data} = await axios.get(URN_MEDIA + "/file?uri=" + fileUrl);
return data;
},
{
refetchOnMount: false,
refetchOnWindowFocus: false,
staleTime: "Infinity",
cacheTime: "Infinity",
enabled: inView,
}
);
But this gets execute whenever the component is re-mounted and the container is in view. Which is obvious because the inView changes from false to true, which in result override the staleTime and cacheTime configurations. I don't want these axios calls to hit if they have data in cache? Any suggestions please. Thanks.
3 Replies
absent-sapphire
absent-sapphire3y ago
Hi. Could you try removing the quotes around Infinity for both cache and staleTime ? "Infinity" is not a valid value (Infinity is), which may explain the override
noble-gold
noble-goldOP3y ago
That was the issue. Thank you so much @glabat
absent-sapphire
absent-sapphire3y ago
Great

Did you find this page helpful?