Home Web Front-end JS Tutorial Complete redux toolkit (Part -

Complete redux toolkit (Part -

Sep 10, 2024 pm 10:35 PM

Complete redux toolkit (Part -

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;
Copy after login

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;
Copy after login

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>Posts</h2>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </section>
  );
};

export default PostsList;
Copy after login

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>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}>
          {isLoading ? 'Adding...' : 'Add Post'}
        </button>
      </form>
    </section>
  );
};

export default AddPostForm;
Copy after login

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;
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1240
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles