In this part we will cover RTK query
1. What is RTK Query?
While Redux Toolkit provides powerful tools to manage state and asynchronous logic, it still requires significant boilerplate code to handle data fetching and caching.RTK Query, introduced in Redux Toolkit v1.6, aims to solve this problem by providing a set of powerful tools for efficient data fetching and caching with minimal setup.
Key features of RTK Query:
To get started with RTK Query, we need to define an API service that specifies how to fetch data and what endpoints are available. Let’s create an example using a simple posts API.
Create a new file named postsApi.js in the features/posts directory. This file will define the API endpoints for fetching and mutating posts.
// src/features/posts/postsApi.js import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; // Define an API service using RTK Query export const postsApi = createApi({ reducerPath: 'postsApi', baseQuery: fetchBaseQuery({ baseUrl: 'https://jsonplaceholder.typicode.com/' }), endpoints: (builder) => ({ fetchPosts: builder.query({ query: () => 'posts', }), addPost: builder.mutation({ query: (newPost) => ({ url: 'posts', method: 'POST', body: newPost, }), }), }), }); // Export hooks for usage in functional components export const { useFetchPostsQuery, useAddPostMutation } = postsApi;
Explanation:
Add the postsApi reducer to the store and configure middleware to enable caching and invalidation.
Update store.js to integrate postsApi:
// src/app/store.js import { configureStore } from '@reduxjs/toolkit'; import { postsApi } from '../features/posts/postsApi'; const store = configureStore({ reducer: { // Add the generated reducer as a specific top-level slice [postsApi.reducerPath]: postsApi.reducer, }, // Adding the api middleware enables caching, invalidation, polling, and other features of RTK Query middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(postsApi.middleware), }); export default store;
RTK Query generates custom hooks based on the endpoints defined in the API service. These hooks are used to perform data fetching, mutations, and manage caching automatically.
Create a PostsList.js component to fetch and display the list of posts.
// src/features/posts/PostsList.js import React from 'react'; import { useFetchPostsQuery } from './postsApi'; const PostsList = () => { const { data: posts, error, isLoading } = useFetchPostsQuery(); if (isLoading) returnLoading...
; if (error) returnAn error occurred: {error.message}
; return (); }; export default PostsList; Posts
{posts.map((post) => (
- {post.title}
))}
Explanation:
Create a AddPostForm.js component to add new posts using the addPost mutation.
// src/features/posts/AddPostForm.js import React, { useState } from 'react'; import { useAddPostMutation } from './postsApi'; const AddPostForm = () => { const [addPost, { isLoading }] = useAddPostMutation(); const [title, setTitle] = useState(''); const [content, setContent] = useState(''); const handleSubmit = async (e) => { e.preventDefault(); if (title && content) { await addPost({ title, body: content }).unwrap(); setTitle(''); setContent(''); } }; return (); }; export default AddPostForm; Add a New Post
Explanation:
RTK Query automatically handles caching, error states, and invalidates the cache when mutations occur. You can further customize the behavior with tags and other configurations.
Modify the postsApi to use tags for cache invalidation:
// src/features/posts/postsApi.js import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; export const postsApi = createApi({ reducerPath: 'postsApi', baseQuery: fetchBaseQuery({ baseUrl: 'https://jsonplaceholder.typicode.com/' }), tagTypes: ['Post'], endpoints: (builder) => ({ fetchPosts: builder.query({ query: () => 'posts', providesTags: (result) => result ? result.map(({ id }) => ({ type: 'Post', id })) : ['Post'], }), addPost: builder.mutation({ query: (newPost) => ({ url: 'posts', method: 'POST', body: newPost, }), invalidatesTags: ['Post'], }), }), }); export const { useFetchPostsQuery, useAddPostMutation } = postsApi;
Explanation:
In this part, we explored how to use RTK Query to handle data fetching and caching in Redux applications. We covered setting up an API service, defining endpoints, and using generated hooks for querying and mutating data. RTK Query simplifies data fetching and state management with minimal code, making it a powerful tool for modern Redux applications.
次のパートでは、クエリのカスタマイズ、baseQuery の使用、認証の処理、パフォーマンスの最適化など、RTK クエリの高度なトピックについて詳しく説明します。
パート 4: RTK クエリの高度なトピックをお楽しみに!
The above is the detailed content of Complete redux toolkit (Part -. For more information, please follow other related articles on the PHP Chinese website!