Part 3: Introduction to RTK Query
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:
- Data Fetching and Caching: Automatically handles caching, invalidation, and refetching.
- Optimistic Updates and Realtime Synchronization: Easily manage optimistic updates and real-time data synchronization.
- Declarative and Simple API: Intuitive API design with minimal boilerplate code.
- Integrated with Redux Toolkit: Built on top of Redux Toolkit, allowing seamless integration.
2. Setting Up 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.
Step 1: Define an API Service
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:
- createApi: This function is used to define an API service. It generates an API slice, automatically managing the store, reducers, and actions for you.
- baseQuery: A function that defines the base URL for your API. fetchBaseQuery is a lightweight wrapper around the standard fetch API.
- endpoints: A function that defines the endpoints for the API. We define two endpoints here: fetchPosts for querying data and addPost for creating a new post.
Step 2: Integrate API Service into the Redux Store
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;
3. Using RTK Query in Components
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.
Step 1: Fetching Data with useFetchPostsQuery
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) return <p>Loading...</p>; if (error) return <p>An error occurred: {error.message}</p>; return ( <section> <h2 id="Posts">Posts</h2> <ul> {posts.map((post) => ( <li key="{post.id}">{post.title}</li> ))} </ul> </section> ); }; export default PostsList;
Explanation:
- useFetchPostsQuery: A custom hook generated by RTK Query for the fetchPosts endpoint. It returns an object containing the fetched data (data), loading state (isLoading), and error state (error).
- The component conditionally renders loading, error, or data states based on the hook output.
Step 2: Adding Data with useAddPostMutation
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 ( <section> <h2 id="Add-a-New-Post">Add a New Post</h2> <form onsubmit="{handleSubmit}"> <input type="text" value="{title}" onchange="{(e)"> setTitle(e.target.value)} placeholder="Post Title" /> <textarea value="{content}" onchange="{(e)"> setContent(e.target.value)} placeholder="Post Content" /> <button type="submit" disabled> {isLoading ? 'Adding...' : 'Add Post'} </button> </textarea> </form> </section> ); }; export default AddPostForm;
Explanation:
- useAddPostMutation: A custom hook generated by RTK Query for the addPost mutation. It provides a function (addPost) to trigger the mutation and a loading state (isLoading).
- unwrap(): Allows us to unwrap the resolved or rejected payload from the mutation to handle side effects after the request.
4. Handling Cache, Errors, and Optimistic Updates
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.
Step 1: Using providesTags and invalidatesTags
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:
- providesTags: This is used to tag the data fetched from the fetchPosts query. It helps in efficiently invalidating the cache when new data is added.
- invalidatesTags: This is used in the addPost mutation to invalidate the cache and refetch the updated data.
5. Conclusion and Next Steps
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!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

This article discusses how to use jQuery to obtain and set the inner margin and margin values of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
