This content originally appeared on Bits and Pieces - Medium and was authored by Suphi Başdemir
Introduction
What is Redux Toolkit Query?
Redux Toolkit Query (RTK Query) is a powerful data fetching and caching tool designed to simplify common cases for loading data in a web application. It is included within the installation of the core Redux Toolkit package and provides access to the Query and React Query APIs. RTK Query is designed to remove the need for manually writing data fetching and caching logic.
What is a Mutation Request?
A mutation request is a potentially destructive query that mutates network data. Mutations are used to send data updates to the server and apply the changes to the local cache. Mutations can also invalidate cached data, allowing applications to re-fetch and update their data. The default HTTP method for a mutation request is a POST. The key difference between a mutation and a query is that mutations are used to change the data while queries are used to access the data.
Invalidating the Cache with a Mutation Request
Examples of Mutation Requests
Mutation requests are used to send data updates to the server and apply the changes to the local cache, using the providesTags property for a query endpoint. Examples of mutation requests include creating new data, updating existing data, and deleting data. In the case of RTK Query, the mutations which can invalidate a cache are the update, create, and delete mutations.
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
import type { Post, User } from './types'
const api = createApi({
baseQuery: fetchBaseQuery({
baseUrl: '/',
}),
tagTypes: ['Post', 'User'],
endpoints: (build) => ({
getPosts: build.query<Post[], void>({
query: () => '/posts',
providesTags: ['Post'],
}),
getUsers: build.query<User[], void>({
query: () => '/users',
providesTags: ['User'],
}),
addPost: build.mutation<Post, Omit<Post, 'id'>>({
query: (body) => ({
url: 'posts',
method: 'POST',
body,
}),
}),
editPost: build.mutation<Post, Partial<Post> & Pick<Post, 'id'>>({
query: (body) => ({
url: `post/${body.id}`,
method: 'POST',
body,
}),
}),
}),
})
How to Invalidate a Cache with a Mutation Request
Invalidating a cache with a mutation request is a straightforward process. First, the mutation request must be dispatched with the Redux store. Once the request is sent, the mutation will be applied to the local cache. The mutation request will then invalidate the cached data, causing RTK Query to refetch the data, using the invalidatesTags property for a mutation endpoint. This will ensure that the most up-to-date data is fetched from the server and applied to the local cache.
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
import type { Post, User } from './types'
const api = createApi({
baseQuery: fetchBaseQuery({
baseUrl: '/',
}),
tagTypes: ['Post', 'User'],
endpoints: (build) => ({
getPosts: build.query<Post[], void>({
query: () => '/posts',
providesTags: (result, error, arg) =>
result
? [...result.map(({ id }) => ({ type: 'Post' as const, id })), 'Post']
: ['Post'],
}),
getUsers: build.query<User[], void>({
query: () => '/users',
providesTags: ['User'],
}),
addPost: build.mutation<Post, Omit<Post, 'id'>>({
query: (body) => ({
url: 'post',
method: 'POST',
body,
}),
invalidatesTags: ['Post'],
}),
editPost: build.mutation<Post, Partial<Post> & Pick<Post, 'id'>>({
query: (body) => ({
url: `post/${body.id}`,
method: 'POST',
body,
}),
invalidatesTags: ['Post'],
}),
}),
})
Conclusion
The main benefit of invalidating a cache with a mutation request is that it ensures that the most up-to-date data is served to the user. The RTK Query API makes it easy to invalidate a cache with a mutation by providing a simple API that requires minimal setup. For more information, see the RTK Query documentation.
RTK Query provides a powerful API for fetching and caching data and that mutation requests can be used to invalidate a cache. Invalidating a cache with a mutation request ensures that the most up-to-date data is served to the user.
Bonus: Build React Apps with reusable components, just like Lego
Bit’s open-source tool help 250,000+ devs to build apps with components.
Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.
Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:
→ Micro-Frontends
→ Design System
→ Code-Sharing and reuse
→ Monorepo
Learn more
- How We Build Micro Frontends
- How we Build a Component Design System
- Bit - Component driven development
- 5 Ways to Build a React Monorepo
- How to Create a Composable React App with Bit
- Sharing JavaScript Utility Functions Across Projects
Redux Toolkit Query: Invalidate a Cache with a Mutation Request was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Suphi Başdemir
Suphi Başdemir | Sciencx (2023-02-17T12:22:20+00:00) Redux Toolkit Query: Invalidate a Cache with a Mutation Request. Retrieved from https://www.scien.cx/2023/02/17/redux-toolkit-query-invalidate-a-cache-with-a-mutation-request/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.