React · Senior · Question 32 of 75

How do you do an optimistic update in RTK Query?

Explanation

dispatch(api.util.updateQueryData('getPost', id, draft => { draft.title = t })) edits the cache with Immer and returns a patch object. In try { await queryFulfilled } catch { patchResult.undo() } the changes are rolled back on error. TanStack Query has a similar approach via onMutate.

Further reading

Problem with a question

React · Senior · question 32

Test yourself

Take the React · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz