React · Senior · Question 32 of 75
How do you do an optimistic update in RTK Query?
- ✓Correct answer:
updateQueryDatainonQueryStarted, rolling back viaundo() - 2Pass an
optimistic: trueflag to the endpoint definition increateApi - 3Call
invalidatesTagsmanually before sending the request to the server
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.