Mutations#
Unlike useQuery, useMutation returns a tuple. The first item in the tuple is the trigger function and the second element contains an object with status, error, and data.
Unlike the useQuery hook, the useMutation hook doesn't execute automatically. To run a mutation you have to call the trigger function returned as the first tuple value from the hook.
- TypeScript
- JavaScript
info
Notice the onQuery method? Be sure to check out how it can be used for optimistic updates
Type interfaces#
Basic Mutation#
This is a modified version of the complete example you can see at the bottom of the page to highlight the updatePost mutation. In this scenario, a post is fetched with useQuery, and then a EditablePostName component is rendered that allows us to edit the name of the post.
Advanced mutations with revalidation#
In the real world, it's very common that a developer would want to resync their local data cache with the server after performing a mutation (aka "revalidation"). RTK Query takes a more centralized approach to this and requires you to configure the invalidation behavior in your API service definition. See Advanced Invalidation with abstract tag IDs for details on advanced invalidation handling with RTK Query.
Example - Commented Posts Service#
This is an example of a CRUD service for Posts. This implements the Selectively invalidating lists strategy and will most likely serve as a good foundation for real applications.
- TypeScript
- JavaScript