Is there a good way to only cache a response if a condition is met, to avoid caching unhappy paths? #6784
Unanswered
Mystagogue
asked this question in
Q&A
Replies: 1 comment 1 reply
-
I don't really understand the problem / use case, sorry. React Query is not tied to status codes. You can return a rejected promise from the queryFn even if you get a 200 status code back... |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Good day all!
I used Tanstack Query on personal projects and I was totally sold, its amazing. I have introduced it on an professional project and quickly encountered a problem.
All responses I get from multiple external services and api gateways are of the form:
type ApiGatewayResponse<T> = { status: ResponseStatus; data: T; messages: IResponseMessage[]; };
There are multiple variants but in all cases the "data" that I am interested in is a property of the body of the response and the response status here is not the http status code but a more nuanced status that is specific to API. Whether this is a good pattern for responses or not is moot as these APIs are completely outside of my control.
You may well say I should throw an error if there is a non 200 status code, but in some of these situations I want to parse the response body and know about the internal status and messages. Sometimes responses have a 200 http status code even when the inner status property is not "success". I still want react-query to present me with this data.
In these situations the possibility exists of react-query caching the unhappy path. A path where I have a body of pertinent messages that I want to present to the user but the internal status is not "success". I only want it to cache IF the internal status is "success".
I feel like I need something like an "onlyCacheIf" property on useQuery that accepts an expression that resolves to a boolean. i.e onlyCacheIf: data?.status === "success"
In truth I have a lot of ways around this but none of them I consider "elegant" and from my experience patterns like this where there is an inner status property in API responses are very common.
I was looking for advice from other people on what they would do in such a situation? I feel like I am missing something obvious?!
Thank you all for your time
Beta Was this translation helpful? Give feedback.
All reactions