0

I am working with RTK query and I have a project that I am working on, where I want to make an API call every 5 seconds (interval), and I do not know the difference between the keepUnusedDataFor and refetchOnMountOrArgsChange property.

Which one should I use to make the API call every 5 seconds.

neil
  • 353
  • 1
  • 8
  • 17

3 Answers3

4

RTK Query keeps an internal counter for each endpoint+cacheKey combination. It increases the counter for each component that wants to read that data, ie, useGetPokemonQuery("pikachu"). When components unmount or change the cache key, it decreases the counter.

When a subscription counter goes to 0, RTK Query sets a timer, and by default that timer is 60s. If no components have asked to read that data when the timer expires, it will remove the data from the cache.

keepUnusedDataFor changes the timer delay. If you set it to, say, 60 * 60, it will wait for one hour before checking if the data should be removed. If you did 60 * 60 * 24 * 365 * 10, it would wait for 10 years before checking to remove the data (ie, "basically forever").

refetchOnMountOrArgChange`, on the other hand, can be used to force re-fetching more often than usual.

See these explanations in the docs:

markerikson
  • 63,178
  • 10
  • 141
  • 157
1

We can make use of polling like this

let {
        data: list,
    } = useGetStocksQuery({tickerArray}, {pollingInterval: 5000});

If we want to skip the query call if args don't have data

let {
        data: list,
    } = useGetStocksQuery({tickerArray}, {pollingInterval: 5000, skip: !tickerArray.length});
jai ganesh
  • 23
  • 4
-1

To anybody from the future, Here is what I came up with, I used refetch which is returned by RTK-query hooks.


// stocks component


import { useGetStocksQuery } from '../features/stocksList/stocksListApiSlice';
import { useEffect, useRef } from "react";

const Stocks = () => {

    const tickerArray = [
        "AAPL",
        "TSLA",
        "NKE",
        "MSFT",
        "AMZN",
        "GOOGL",
        "META",
        "SNAP",
        "NFLX"
    ];


    const stockTimerId = useRef();


   let {
        data: list,
        refetch
    } = useGetStocksQuery({tickerArray});


    useEffect(() => {

   stockTimerId.current = await setInterval(() => refetch(), 10000);

  }

        return () => clearInterval(stockTimerId.current)
    })


return (
  <>Your JSX goes here</>
)

}

export default Stocks

neil
  • 353
  • 1
  • 8
  • 17
  • why not use the `pollingInterval` option on the query? – Kurtis Streutker Mar 16 '23 at 13:35
  • @KurtisStreutker - Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center. – neil Mar 26 '23 at 10:41