Optimistic Updates with RTK Query

Lada496
2 min readMay 28, 2023

This is my memo from when I implemented optimistic updates with RTK Query.
Below is the final result of what I implemented. Both the “add to cart” and “add to wishlist” buttons send requests to the server to process these actions, the browser side acts like the client side manages these data.

video of optimistic updates

We can leverage onQueryStarted to implement that feature. Here is an example of onQueryStarted usage.

async onQueryStarted({ cartItemToAdd }, { dispatch, queryFulfilled }) {
const patchResult = dispatch(
cartApi.util.updateQueryData("getCartItems", undefined, (draft) => {
const updatedCartItems = addItemToCart(
draft.cartItems,
cartItemToAdd
);
return {
...draft,
cartItems: updatedCartItems,
};
})
);
try {
await queryFulfilled;
} catch {
patchResult.undo();
}

Trouble shooting

Here are some mistakes I make made during the development process.

  • TypeError: Cannot read properties of undefined (reading ‘select’)

If you got this error message you might pass a wrong query name at updateQueryData.

--

--