Search code examples
reduxredux-toolkitrtk-query

Is it possible to optimistically update all caches of a endpoint?


In the redux tutorial, we learned how to perform optimistic updates:

part-8-rtk-query-advanced#implementing-optimistic-updates

But in the API reference of updateQueryData, I found that an args must be passed in:

const updateQueryData = (
  endpointName: string,
  args: any,
  updateRecipe: (draft: Draft<CachedState>) => void
) => ThunkAction<PatchCollection, PartialState, any, AnyAction>;

So, if our post has pagination,

getPosts: builder.query({
  query: (current: number) => `/posts?current=${current}`,
  providesTags: ['Post']
}),

At this time, how will we perform an optimistic update?

// Is there a way to update all getPosts caches?
// Am I missing some documents?
apiSlice.util.updateQueryData('getPosts', ???, (draft) => {
  const post = draft.find((post) => post.id === postId)
  if (post) {
    post.reactions[reaction]++
  }
})


Solution

  • Since Redux Toolkit 1.7, that is possible.

    It contains a api.util.selectInvalidatedBy helper function that allows you to get all endpoints with arguments that provided a specific tag.

    It can be used as following:

       async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled, getState }) {
         for (const { endpointName, originalArgs } of api.util.selectInvalidatedBy(getState(), [{ type: "Post", id}])) { 
           // we only want to update `getPosts` here
           if ( endpointName !== 'getPosts') continue;
           dispatch(
             api.util.updateQueryData(endpoint, originalArgs, (draft) => {
                // find in list & update
             })
           )
         }, 
       },