Home > OS >  how to stop refetchInterval react query (useQuries) after 3 times repeat?
how to stop refetchInterval react query (useQuries) after 3 times repeat?

Time:10-18

Here i am using react Query to fetch data. i have used in useQuries refetchInterval for 3000 miliseconds, so every 3 seconds it's refetch data. so when i display data it's changing automatically as we refetch data. but in my case i don't want to refetch data more then 3 times, suppose, i want to use {refetchInterval : 3000} only for 3 times then it will stop refetching data.

is there any way to do this. how can i fix it for only 3 times use refetchInterval options. ecah time it will refetch after 3 seconds and onec it refetch 3 times it will automatically stop and no more reftech will work.

Please Help me to fix this and break the refetchInterval after 3 times. ThankYou for your trying in advance!

  const fetchData = () => {
            const rA=  devices?.map(async (id) => {
                const info = await axios.get(`https://www.roads.com/road/api/roadControl/${id}`, myHeaders).then((res) => {
                    return res.data;
                })
                return info
                
            })
            
            return rA;
        };
    
        const { data } = useQuery("post", fetchData,
            { refetchInterval: 3000 });

CodePudding user response:

This should work

const countRef = useRef(0)
const { data } = useQuery("post", () => {
  countRef.current  = 1
  return fetchData()
}, { refetchInterval: () => countRef.current < 3 ? 3000 : false });
  • Related