0Pricing
tRPC End-to-End Type Safe APIs · บทเรียน

การปรับปรุงข้อมูลเชิงคาดการณ์

เรียนรู้การมอบประสบการณ์ที่ตอบสนองทันทีแก่ผู้ใช้ด้วยการใช้งานการปรับปรุงข้อมูลเชิงคาดการณ์ร่วมกับ tRPC และแคชฝั่งไคลเอนต์

การปรับปรุงข้อมูลเชิงคาดการณ์ เป็นบทเรียน tRPC End-to-End Type Safe APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน tRPC End-to-End Type Safe APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส tRPC End-to-End Type Safe APIs มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Instant Feedback with Optimistic Updates

Imagine clicking 'Like' on a post. You expect it to show 'Liked' instantly, right? That's the magic of Optimistic Updates!

Optimistic updates make your app feel incredibly fast and responsive. They improve the user experience by giving immediate feedback.

What Are Optimistic Updates?

An optimistic update means updating the user interface (UI) before the server has confirmed the change. You 'optimistically' assume the server request will succeed.

  • Instant UI update: The user sees their action immediately reflected.
  • Background server call: The actual data change is sent to the backend.
  • Rollback on error: If the server fails, the UI reverts to its previous state.

Why Use Them with tRPC?

tRPC, combined with a client-side caching library like React Query (or TanStack Query), provides powerful tools for managing server state and implementing optimistic updates.

React Query's useMutation hook is central to this. It allows you to define callbacks for when a mutation starts, succeeds, or fails, enabling precise control over the UI.

The `onMutate` Callback

When you trigger a mutation, React Query calls the onMutate function before sending the request to the server. This is where you perform the optimistic UI update.

Inside onMutate, you typically:

  • Cancel any ongoing fetches for the data you're about to change.
  • Snapshot the current data so you can roll back if needed.
  • Update the cache with the new, optimistic data.

Setting Up `onMutate`

Let's look at a simplified example for 'liking' a post. We'll use queryClient.setQueryData to update the cache optimistically.

import { trpc } from '../utils/trpc';
import { useQueryClient } from '@tanstack/react-query';

function PostLikeButton({ postId }: { postId: string }) {
  const queryClient = useQueryClient();
  const likeMutation = trpc.post.like.useMutation({
    onMutate: async (newLike) => {
      // 1. Cancel any outgoing refetches
      await queryClient.cancelQueries(['post', postId]);

      // 2. Snapshot the previous value
      const previousPost = queryClient.getQueryData(['post', postId]);

      // 3. Optimistically update to the new value
      queryClient.setQueryData(['post', postId], (old: any) => {
        if (old) {
          return { ...old, likes: old.likes + 1, isLiked: true };
        }
        return old;
      });

      return { previousPost }; // Context for onError
    },
  });

  return (
    <button onClick={() => likeMutation.mutate({ postId })}>Like</button>
  );
}

The `onError` Callback

If the server mutation fails, you need to revert the UI to its previous state. This is handled in the onError callback.

Here, you use the context object returned from onMutate (which holds your snapshot of previousPost) to restore the cache to its original value.

Implementing `onError` (Rollback)

Adding the onError handler to our useMutation setup:

import { trpc } from '../utils/trpc';
import { useQueryClient } from '@tanstack/react-query';

function PostLikeButton({ postId }: { postId: string }) {
  const queryClient = useQueryClient();
  const likeMutation = trpc.post.like.useMutation({
    onMutate: async (newLike) => {
      // ... (same as before)
      const previousPost = queryClient.getQueryData(['post', postId]);
      queryClient.setQueryData(['post', postId], (old: any) => {
        if (old) return { ...old, likes: old.likes + 1, isLiked: true };
        return old;
      });
      return { previousPost };
    },
    onError: (err, newLike, context) => {
      // Rollback the cache to the previousPost
      queryClient.setQueryData(['post', postId], context?.previousPost);
      // Optionally show an error toast
      console.error("Failed to like post: ", err.message);
    },
  });

  return (
    <button onClick={() => likeMutation.mutate({ postId })}>Like</button>
  );
}

The `onSuccess` Callback

Once the server successfully processes the mutation, the onSuccess callback is triggered. At this point, your optimistic UI update is correct, but you still want to ensure data consistency.

The best practice here is to invalidate relevant queries. This tells React Query to refetch the data in the background, ensuring your client-side cache is perfectly in sync with the server.

Completing the Optimistic Flow

Here's the full useMutation with onSuccess to invalidate and refetch data after a successful server response:

import { trpc } from '../utils/trpc';
import { useQueryClient } from '@tanstack/react-query';

function PostLikeButton({ postId }: { postId: string }) {
  const queryClient = useQueryClient();
  const likeMutation = trpc.post.like.useMutation({
    onMutate: async (newLike) => {
      await queryClient.cancelQueries(['post', postId]);
      const previousPost = queryClient.getQueryData(['post', postId]);
      queryClient.setQueryData(['post', postId], (old: any) => {
        if (old) return { ...old, likes: old.likes + 1, isLiked: true };
        return old;
      });
      return { previousPost };
    },
    onError: (err, newLike, context) => {
      queryClient.setQueryData(['post', postId], context?.previousPost);
      console.error("Failed to like post: ", err.message);
    },
    onSuccess: () => {
      // Invalidate and refetch the post data to ensure consistency
      queryClient.invalidateQueries(['post', postId]);
    },
  });

  return (
    <button onClick={() => likeMutation.mutate({ postId })}>Like</button>
  );
}

Benefits and Considerations

Optimistic updates are fantastic for user experience, but they add complexity:

  • Pro: Instant UI feedback, perceived performance boost.
  • Pro: Reduces loading spinners and waiting times.
  • Con: Requires careful rollback logic for errors.
  • Con: Can be complex for operations that depend on server-generated IDs or complex data transformations.

Use them thoughtfully, especially for actions where immediate feedback is critical and conflicts are rare.

Check Your Understanding

Consider an optimistic update for adding an item to a shopping cart. Which of the following actions are typically performed within the onMutate callback?

Recap: Optimistic Updates

In this lesson, we explored optimistic updates, a powerful technique to enhance user experience by providing instant feedback.

  • We learned how onMutate is used to optimistically update the UI and prepare for potential rollbacks.
  • We saw how onError handles reverting the UI to its previous state if the server request fails.
  • Finally, we covered how onSuccess ensures data consistency by invalidating and refetching data after a successful server response.

Mastering optimistic updates helps you build highly responsive and user-friendly tRPC applications!

คำถามที่พบบ่อย

บทเรียน “การปรับปรุงข้อมูลเชิงคาดการณ์” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การปรับปรุงข้อมูลเชิงคาดการณ์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส tRPC End-to-End Type Safe APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส tRPC End-to-End Type Safe APIs มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การปรับปรุงข้อมูลเชิงคาดการณ์”

เรียนรู้การมอบประสบการณ์ที่ตอบสนองทันทีแก่ผู้ใช้ด้วยการใช้งานการปรับปรุงข้อมูลเชิงคาดการณ์ร่วมกับ tRPC และแคชฝั่งไคลเอนต์ คุณปฏิบัติ tRPC End-to-End Type Safe APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน tRPC End-to-End Type Safe APIs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน tRPC End-to-End Type Safe APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การปรับปรุงข้อมูลเชิงคาดการณ์” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน tRPC End-to-End Type Safe APIs นี้ได้ไหม

ได้ บทเรียน tRPC End-to-End Type Safe APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การแบ่งคำขอเป็นชุดอย่างมีประสิทธิภาพ
  2. การปรับปรุงข้อมูลเชิงคาดการณ์
  3. การอัปโหลดไฟล์ด้วย tRPC
  4. คำค้นไม่สิ้นสุดและการแบ่งหน้าโดยใช้เคอร์เซอร์
← กลับไปที่ tRPC End-to-End Type Safe APIs