RTK query update state

June 11, 2022

Let’s say you want to update your cart items, adding an egg for example.

Current state

{
  quantity: 1;
  product: "Milk";
}

You send your request to the API endpoint. The problem is your backend already sent the updated cart list on your first request.

[
  {
    quantity: 1
    product: 'Milk'
  },
  {
    quantity: 1
    product: 'Egg'
  }
]

By the default RTK will use Automated Re-fetching .This will add one more fetch than what was needed. Invalidate tags will trigger a refetch, the problem is the page will reload, which is not what you want if you are using React.

The solution is to use Manual cache updates

        updateCart: builder.mutation({
            query: body => ({
                url: '/cart/',
                method: 'PUT',
                body,
            }),
            async onQueryStarted(body, { dispatch, queryFulfilled }) {
                try {
                    const { data } = await queryFulfilled
                    dispatch(
                        cartApi.util.updateQueryData('getCart', {}, (draft: any) => {

                            const payload = data.cart[data.cart.length - 1]

                            draft.push({
                              id: payload.id,
                              quantity: payload.id,
                              product: payload.product
                            })
                        }),
                    )
                } catch (err) {
                    console.log(err, 'err')
                }
            },
        }),

updateQueryData does not update state

Common mistakes:

Not passing what was required.

https://github.com/reduxjs/redux-toolkit/issues/1355