Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]++
  }
})

like image 605
Grapes Avatar asked Oct 14 '25 19:10

Grapes


1 Answers

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
         })
       )
     }, 
   },
like image 66
phry Avatar answered Oct 17 '25 22:10

phry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!