Home > Back-end >  how to do an optimistic update with injectEndpoints
how to do an optimistic update with injectEndpoints

Time:01-24

How to create an optimistic update with redux toolkit using the injectEndpoints builder? I have an api call structured this way

import api from './api';

export const heartApi = api.injectEndpoints({
    endpoints: (builder) => ({
        createHeart: builder.mutation({
            query: (id: string) => ({ url: '/hearts', method: 'POST', body: { id } }),
        }),
    }),
});

export const { useCreateHeartMutation } = heartApi;

the docs mentions that you can use onQueryStarted to optimistically update the cache of a request based on that mutation, however I don't know where to find that using the injectEndpoints method.

CodePudding user response:

There is absolutely no difference between using createApi or injectEndpoints here, in both cases it is part of the builder.mutation call:


export const heartApi = api.injectEndpoints({
    endpoints: (builder) => ({
        createHeart: builder.mutation({
            query: (id: string) => ({ url: '/hearts', method: 'POST', body: { id } }),
            onQueryStarted(arg, {queryFulfilled}){
              // it would go here
            }
        }),
    }),
});
  •  Tags:  
  • Related