Home > Software engineering >  How to save the results of a mutation in Redux toolkit createAPI for later usage?
How to save the results of a mutation in Redux toolkit createAPI for later usage?

Time:11-18

I have lately started using RTK query for fetching data in my application. In one the use cases, I want to use the result of a createAPI mutation where I have created a resource on a server once. This involves creating a specific payload.

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const createResource = createApi({
  reducerPath: 'someReducerPath',
  baseQuery: fetchBaseQuery({ baseUrl: window.API_URL }),
  endpoints: (builder) => ({
    postResource: builder.query({
      // postBody in the parameter is received from the caller function.
      //It is an object containing the payload
      query: (postBody) => ({
        url: 'someURL',
        method: 'POST',
        body: postBody
      }),
      transformResponse: (response) => response
    }),
  }),
});

// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { usePostResourceQuery } = createResource;

If I want to use the same result from this mutation in another component or another place, how to do it without actually creating the same payload? Do I have to dispatch the results to a different slice where it could be stored, or can we somehow refer to the result received from the above mutation?

CodePudding user response:

Ideally, Mutations (POST/ PUT) are not expected to return anything in repose, rather should be configured to invalidate query tags, so that fetch can be re-triggered. But, i do get the point that in certain situations (to get the data), one has to trigger the mutation.

So, there are two approaches to achieve the same (get access to mutation's response):

  1. When using useMutation, mutation results gets removed from the rtk-query's store key ie. api as soon as component unmounts (basically unsubscribed). So, the only option is to save the results in the separate store key (slice), which can be referenced later.
const handleSubmit = async () => {
  try {
    const data = await mutationFn(PAYLOAD_BODY).unwrap();
    dispatch(SAVE_MUTATION_RESULT(data)); // save the results
  } catch(err) {
    console.error(err);
  }
};
  1. use fixedCacheKey option to tag the mutation and using the dipatch action method to trigger the mutation, which basically interprets as subscribed and then let the subscription live (don't unsubscribe), so that response stays in the rtk-query's store key(api), which you can query as and when needed.
const subcription = dispatch(createResource.endpoints.postResource.initiate(PAYLOAD_BODY, {
    fixedCacheKey: "postResource",
}));

// unsubscribe carefully, (so that don't endup removing the result from store)
subcription.unsubscribe()

Now, To get the response back, in any other component, may be on the same page or altogether the different route, query back with the same key:

const  [, {data}] = useMutation({
    fixedCacheKey: "postResource",
})

if the muttaion & its results exists in the store, you'll get the data back.

Useful links:

Thanks, Manish

  • Related