I've read about RTK query, I'm interested as it removes the hassle of writing slices & thunk action creators. However, I don't think I will want to use the cache invalidation feature. For example, in this sandbox: https://codesandbox.io/s/github/reduxjs/redux-essentials-example-app/tree/checkpoint-5-createApi/?from-embed when switching between tabs, e.g. from Notifications to Posts, I would always want to fetch Posts, but in this example, it follows the cache timer. Should I still use RTK query if I don't use the cache invalidation feature? If yes, what are clean ways to make sure when I call a component with a call to query hook, it will always fetch? Should I set the cache timer to 0s? Thanks
1 Answer
You can use refetchOnMountOrArgChange either globally or as a query hook option. Using true will always fetch, using a number allows you to set a maximum age after which a refetch occurs.
const { data } = useGetPostsQuery(
{ count: 5 },
// this overrules the api definition setting,
// forcing the query to always fetch when this component is mounted
{ refetchOnMountOrArgChange: true }
)
6 Comments
nanakondor
thanks. but is it advisable to use RTK query when i dont need the cache invalidation ?
phry
It still does a lot of other stuff for you that you would have to do by hand if you were just using Redux for it. And if you switch to another lib as React-Query or swr, you essentially get the same functionality there. So I don't see a good reason for switching tbh. The tag system is only one of many features.
Zeeshan Ahmad Khalil
I am using
{ refetchOnMountOrArgChange: true } and my component is mounting every time I am visiting it. But query is getting called only the first time.phry
@ZeeshanAhmadKhalil if there is currently a request going on, even with
refetchOnMountOrArgChange it will wait for the existing query to finish. Maybe that's what you're seeing.Zeeshan Ahmad Khalil
@phry Thank you for replying. I checked in networks I don't have any requests going on. When I am using a parameter, say
{ count: 5 } then { refetchOnMountOrArgChange: true } works fine. But if I am using an empty object for parameter {} then { refetchOnMountOrArgChange: true } is not working. |