Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RTK query `use*Query` is using cached isLoading and data even for different args

I'm new to RTK query and I'm having issues with it sharing data across queries with different args.

// api.js
const { useGetStuffQuery } = api.injectEndpoints({
  endpoints: (builder) => ({
    getStuff: builder.query({
      query: (stuffId) => ({ url: `http://some.random-url.com/${stuffId}` }),
    }),
  }),
});

// component.js
function(props) {
  const [id, setId] = useState(1);
  const { data, isLoading } = useGetStuffQuery(id);

  if (val === '2') {
    console.log('datttt', data); // this initially prints data from id:1
  }

  return <div>
      <input value={id} onChange={(e) => setId(e.target.value)} />
      {
        isLoading ? <span>loading...</span>
                  : <span>data is: {data}</span>
      }

  </div>
}

I was expecting to see the loading indicator to show up once I changed the id from 1 to 2.

However, it seems like rtkQuery is still using the cached data from my previous useGetStuffQuery(1) call and hence I see the data for id1 momentarily. Once the request for id2 is resolved -- it does update and rerender my component.

Is this caching behavior intentional and expected? Or am I missing something?

like image 840
enrij Avatar asked Mar 06 '26 11:03

enrij


1 Answers

It is intentional, there are isLoading and isFetching that are behaving different (isLoading until there is data, isFetching while any request is running) and for convenience the hook will always give you the last data that was known so your UI jumps less.

This is explained in the "Query Loading State" docs section:

isLoading refers to a query being in flight for the first time for the given endpoint + query param combination. No data will be available at this time.

isFetching refers to a query being in flight for the given endpoint + query param combination, but not necessarily for the first time. Data may be available from an earlier request at this time.

like image 147
phry Avatar answered Mar 09 '26 18:03

phry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!