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

Complete redux toolkit (Part - 4)

Sep 11, 2024 pm 02:32 PM

Complete redux toolkit (Part - 4)

Part 4: Advanced Topics in RTK Query.

This part will focus on advanced features and use cases in RTK Query, including customising queries, handling authentication, optimistic updates, and performance optimisation.

Part 4: Advanced Topics in RTK Query

1. Introduction to Advanced RTK Query Concepts

In the previous part, we covered the basics of using RTK Query for fetching and mutating data. Now, we will dive into more advanced features that make RTK Query even more powerful. These features allow you to customize queries, manage authentication, optimize performance, and handle optimistic updates for a smoother user experience.

2. Customizing baseQuery for Authentication

When working with APIs that require authentication, you need to customize the baseQuery to include authentication headers like JWT tokens or API keys.

Step 1: Create a Custom baseQuery

You can create a custom baseQuery function that adds authorization headers to every request.

// src/app/customBaseQuery.js
import { fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const customBaseQuery = fetchBaseQuery({
  baseUrl: 'https://jsonplaceholder.typicode.com/',
  prepareHeaders: (headers, { getState }) => {
    const token = getState().auth.token; // Assuming auth slice has token
    if (token) {
      headers.set('Authorization', `Bearer ${token}`);
    }
    return headers;
  },
});

export default customBaseQuery;
Copy after login

Explanation:

  • prepareHeaders: This function allows you to customize headers for each request. It retrieves the token from the Redux store and attaches it to the Authorization header.

Step 2: Use the Custom baseQuery in createApi

Modify your postsApi.js file to use the custom baseQuery:

// src/features/posts/postsApi.js
import { createApi } from '@reduxjs/toolkit/query/react';
import customBaseQuery from '../../app/customBaseQuery';

export const postsApi = createApi({
  reducerPath: 'postsApi',
  baseQuery: customBaseQuery, // Use the custom base query here
  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

3. Optimistic Updates with RTK Query

Optimistic updates allow you to immediately update the UI before the server confirms the mutation, providing a smoother user experience. If the server returns an error, the UI can revert to the previous state.

Step 1: Implement Optimistic Updates in Mutations

You can implement optimistic updates using the onQueryStarted lifecycle method provided by RTK Query.

// src/features/posts/postsApi.js
addPost: builder.mutation({
  query: (newPost) => ({
    url: 'posts',
    method: 'POST',
    body: newPost,
  }),
  invalidatesTags: ['Post'],
  onQueryStarted: async (newPost, { dispatch, queryFulfilled }) => {
    // Optimistic update: immediately add the new post to the cache
    const patchResult = dispatch(
      postsApi.util.updateQueryData('fetchPosts', undefined, (draftPosts) => {
        draftPosts.push({ id: Date.now(), ...newPost }); // Fake ID for optimistic update
      })
    );
    try {
      await queryFulfilled; // Await server response
    } catch {
      patchResult.undo(); // Revert if the mutation fails
    }
  },
}),
Copy after login

Explanation:

  • onQueryStarted: This lifecycle method is triggered when a mutation starts. It provides dispatch and queryFulfilled parameters to manage cache updates.
  • postsApi.util.updateQueryData: This utility function allows you to optimistically update cached data.
  • patchResult.undo(): Reverts the optimistic update if the server returns an error.

4. Handling Dependent Queries

Sometimes, you may need to perform dependent queries, where one query depends on the result of another. RTK Query provides the skip parameter to control when a query is executed.

Example: Fetch Post Details Based on Selected Post ID

// src/features/posts/PostDetails.js
import React from 'react';
import { useFetchPostQuery } from './postsApi';

const PostDetails = ({ postId }) => {
  const { data: post, error, isLoading } = useFetchPostQuery(postId, { skip: !postId });

  if (!postId) return <p>Select a post to view details.</p>;
  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>Error loading post details.</p>;

  return (
    <div>
      <h3>{post.title}</h3>
      <p>{post.body}</p>
    </div>
  );
};

export default PostDetails;
Copy after login

Explanation:

  • useFetchPostQuery: A query hook that takes postId as an argument. If postId is not provided, the query is skipped using { skip: !postId }.

5. Polling and Real-Time Data with RTK Query

RTK Query supports polling to keep data fresh at a specified interval. This is useful for real-time data synchronization.

Step 1: Use Polling in Queries

You can enable polling for any query using the pollingInterval option.

// src/features/posts/PostsList.js
import React from 'react';
import { useFetchPostsQuery } from './postsApi';

const PostsList = () => {
  const { data: posts, error, isLoading } = useFetchPostsQuery(undefined, {
    pollingInterval: 30000, // Poll every 30 seconds
  });

  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:

  • pollingInterval: This option specifies the interval (in milliseconds) at which the query should poll the server for new data.

6. Optimizing Performance with selectFromResult

RTK Query provides the selectFromResult option for advanced performance optimizations by allowing you to select specific data from the query result.

Step 1: Using selectFromResult to Optimize Re-Renders

The selectFromResult option can be used to prevent unnecessary re-renders when only a subset of the query result is needed.

// src/features/posts/PostTitleList.js
import React from 'react';
import { useFetchPostsQuery } from './postsApi';

const PostTitleList = () => {
  const { data: posts } = useFetchPostsQuery(undefined, {
    selectFromResult: ({ data }) => ({ titles: data?.map((post) => post.title) }),
  });

  return (
    <section>
      <h2>Post Titles</h2>
      <ul>
        {posts?.map((title, index) => (
          <li key={index}>{title}</li>
        ))}
      </ul>
    </section>
  );
};

export default PostTitleList;
Copy after login

Explanation:

  • selectFromResult: This option allows you to select only the titles from the fetched posts, preventing unnecessary re-renders when other data in the query result changes.

7. Conclusion and Next Steps

In this part, we explored advanced topics in RTK Query, such as customizing baseQuery for authentication, handling optimistic updates, managing dependent queries, using polling for real-time data synchronization, and optimizing performance with selectFromResult. RTK Query's rich feature set makes it a powerful tool for handling data fetching and caching in modern Redux applications.

In the next part, we'll discuss Testing Strategies for Redux Toolkit and RTK Query, covering unit testing, integration testing, and best practices for ensuring robust and maintainable code.

Stay tuned for Part 5: Testing Strategies for Redux Toolkit and RTK Query!

The above is the detailed content of Complete redux toolkit (Part - 4). 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
1663
14
PHP Tutorial
1266
29
C# Tutorial
1237
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.

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.

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.

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

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.

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

See all articles