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

1

11

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?

Ternary answered 2/7, 2021 at 5:31 Comment(0)
D
23

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.

Doodlesack answered 2/7, 2021 at 9:10 Comment(3)
ah interesting. the "given endpoint + query param combination" phrase made me think that different query params will be treated uniquely.Ternary
Good point, that could need some slight rewording. Generally: if the hook ever had data before, it will always enter isFetching, but never go into isLoading again.Doodlesack
a note, coming here a year later - the docs have been updated - the "+ query param combination" part was removed from the docs for isLoadingRobynroc

© 2022 - 2024 — McMap. All rights reserved.