Home > Mobile >  How to use RTK query but always fetch
How to use RTK query but always fetch

Time:03-03

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

CodePudding user response:

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 }
  )
  • Related