0

I'm using RTK Query to GET some data

  1. initial GET request returns 200 OK with some data
  2. in some minutes data on server is deleted
  3. I have refetchOnFocus enabled so my GET request is repeated in some time and now it returns 404 error
  4. But use*Query still returns cached data (instead of undefined or something)

My component is based on this data - so UI never knows what where is no more data.

So, why use*Query does not clean the state on 404 error received?

1 Answers1

0

In a lot of cases you actually want to be able to access the last data before an error occured - for example by displaying that data and the error side by side. That is why your query result has an isError and isSuccess property that you should not be ignoring in your code.

phry
  • 35,762
  • 5
  • 67
  • 81
  • Thanks! That makes sense. But that means that the data will stay in cache forever and never becomes undefined? – Michael Jun 16 '22 at 11:36
  • Also I noticed that if my initial request ends up with 404, on the following refetch isLoading becomes true (which leads to recurring 'AppLoading...' splash screen in my case) - that's because there is no cache data as there were no 200 OK responses? – Michael Jun 16 '22 at 11:45
  • @Michael the data will stay in cache until none of your component uses it - then it will be deleted after 60 seconds. And yes, `isLoading` is always true if there is no data yet since usually the two cases to handle in most apps are "data is loaded once" vs "data is here and we wait for a refetch" - "thing is not there and we wait for a refetch is not really an "expected" outcome. – phry Jun 16 '22 at 12:33
  • That said, as in your case it is not really an error, but an expected outcome maybe you just want to change the "404" from an error to a success? See [validateStatus](https://redux-toolkit.js.org/rtk-query/api/fetchBaseQuery#handling-non-standard-response-status-codes) – phry Jun 16 '22 at 12:34
  • You're right, my 404 error is a 'logical' error meaning there is not data in DB rather than web-server 404 error. Currently I'm playing with queryFulfilled and updateCacheData to set data to undefined once I got error but it seems not working as after updateCacheData(() => undefined) I still see cached data in my component, so will try validateStatus – Michael Jun 16 '22 at 12:54
  • Finally, I ended up with {data && !isError && <>show UI>} as advised in the 1st answer – Michael Jun 16 '22 at 14:02