Redux Toolkit Query: Reduce state from "mutation" response
Asked Answered
S

1

7

Let's say I have an RESTish API to manage "posts".

  • GET /posts returns all posts
  • PATCH /posts:id updates a post and responds with new record data

I can implement this using RTK query via something like this:

const TAG_TYPE = 'POST';

// Define a service using a base URL and expected endpoints
export const postsApi = createApi({
  reducerPath: 'postsApi',
  tagTypes: [TAG_TYPE],
  baseQuery,
  endpoints: (builder) => ({
    getPosts: builder.query<Form[], string>({
      query: () => `/posts`,
      providesTags: (result) =>
        [
          { type: TAG_TYPE, id: 'LIST' },
        ],
    }),
    updatePost: builder.mutation<any, { formId: string; formData: any }>({
      // note: an optional `queryFn` may be used in place of `query`
      query: (data) => ({
        url: `/post/${data.formId}`,
        method: 'PATCH',
        body: data.formData,
      }),
      // this causes a full re-query.  
      // Would be more efficient to update state based on resp.body
      invalidatesTags: [{ type: TAG_TYPE, id: 'LIST' }],
    }),
  }),
});

When updatePost runs, it invalidates the LIST tag which causes getPosts to run again.

However, since the PATCH operation responds with the new data itself, I would like to avoid making an additional server request and instead just update my reducer state for that specific record with the content of response.body.

Seems like a common use case, but I'm struggling to find any documentation on doing something like this.

Shoestring answered 20/9, 2021 at 20:19 Comment(0)
M
8

You can apply the mechanism described in optimistic updates, just a little bit later:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
import { Post } from './types'

const api = createApi({
  // ...
  endpoints: (build) => ({
    // ...
    updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
      query: ({ id, ...patch }) => ({
        // ...
      }),
      async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
        const { data } = await queryFulfilled
        dispatch(
          api.util.updateQueryData('getPost', id, (draft) => {
            Object.assign(draft, data)
          })
        )
      },
    }),
  }),
})
Mouseear answered 20/9, 2021 at 21:0 Comment(1)
ah that makes sense. I think the onQueryStarted threw me off the scent. Thanks!Shoestring

© 2022 - 2024 — McMap. All rights reserved.