Search code examples
javascriptreactjsreduxredux-toolkitrtk-query

Need RTK-query mutation data in multiple components in ReactJS


I am using React 18 with @reduxjs/toolkit 1.9.1.

On form Submit, a post API is triggered using RTK-mutation and used the response in the component. The page navigates successfully. Check the code below.

const formSubmit = async (data) => {
  const payload = {
    ...
  };

  try {
    const response = await artistSearch(payload);

    if (response) {
      navigate("/artist-search-results", { state: { data } });
    }
  } catch (artistError) {
    ...
  }
};  

using the relevant API

export const artistApi = createApi({
  reducerPath: "artistApi",
  baseQuery: fetchBaseQuery({
    baseUrl: `...`,
    headers: { ... },
  }),
  endpoints: (builder) => ({
    getArtist: builder.query({
      query: (uid) => `/getProfile/${uid}`,
    }),
    artistSearch: builder.mutation({
      query: (formData) => ({
        url: "ArtistListSearch",
        method: "POST",
        body: formData,
      }),
    }),
  }),
});

export const { useGetArtistQuery, useArtistSearchMutation } = artistApi;

Now I am failing to use the artistSearch mutation response data in the component which is rendering just where the page navigates to. IOW, I want to use artistSearch mutation response data in other components also.

I have tried via following code, but getting undefined in the console.

const [
  artistSearch,
  {
    data: artistSearchResponse,
    error: artistError,
    isLoading: isArtistLoading
  }
] = useArtistSearchMutation();
console.log("artist search data is:", artistSearchResponse);

Solution

  • You can used a specific cache key on the mutation such that other components using the same mutation can access the same cached results.

    See useMutation: fixedCacheKey

    type UseMutationStateOptions = {
      // A method to determine the contents of `UseMutationResult`
      selectFromResult?: (result: UseMutationStateDefaultResult) => any
      // A string used to enable shared results across hook instances which have the same key
      fixedCacheKey?: string
    }
    

    Example:

    const [artistSearch] = useArtistSearchMutation({
      fixedCacheKey: "artistSearch",
    });
    
    const formSubmit = async (data) => {
      const payload = {
        ...
      };
    
      try {
        const response = await artistSearch(payload).unwrap();
    
        if (response) {
          navigate("/artist-search-results", { state: { data } });
        }
      } catch (artistError) {
        ...
      }
    };  
    
    const [
      artistSearch,
      {
        data: artistSearchResponse, // should be same cached data from above
        error: artistError,
        isLoading: isArtistLoading
      }
    ] = useArtistSearchMutation({
      fixedCacheKey: "artistSearch",
    });