Skip to main content

Lesson 8 of 8

Practice & Quiz - Data Fetching & APIs

Test your mastery of TanStack Query mutations, optimistic updates, race condition prevention, and WebSocket integration with a practical exercise and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical Exercise - Optimistic Todo List with TanStack Query

Practical Exercise - Optimistic Todo List with TanStack Query
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';

interface Todo { id: number; title: string; completed: boolean; }

const api = axios.create({ baseURL: 'https://jsonplaceholder.typicode.com' });

// โ”€โ”€โ”€ Queries โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
function useTodos() {
  return useQuery<Todo[]>({
    queryKey: ['todos'],
    queryFn: () => api.get('/todos?_limit=5').then(r => r.data),
    staleTime: 30_000,  // consider fresh for 30s
  });
}

// โ”€โ”€โ”€ Mutation with optimistic update โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
function useToggleTodo() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, completed }: { id: number; completed: boolean }) =>
      api.patch(`/todos/${id}`, { completed }),

    // 1. Before request: update cache immediately
    onMutate: async ({ id, completed }) => {
      await qc.cancelQueries({ queryKey: ['todos'] });
      const prev = qc.getQueryData<Todo[]>(['todos']);

      qc.setQueryData<Todo[]>(['todos'], (old) =>
        old?.map(t => t.id === id ? { ...t, completed } : t) ?? []
      );
      return { prev }; // snapshot for rollback
    },

    // 2. On error: roll back to snapshot
    onError: (_err, _vars, context) => {
      if (context?.prev) qc.setQueryData(['todos'], context.prev);
    },

    // 3. Always: refetch to sync with server
    onSettled: () => qc.invalidateQueries({ queryKey: ['todos'] }),
  });
}

// โ”€โ”€โ”€ Component โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
export function TodoList() {
  const { data: todos, isLoading, isError } = useTodos();
  const toggle = useToggleTodo();

  if (isLoading) return <p>Loading...</p>;
  if (isError)   return <p>Error loading todos</p>;

  return (
    <ul>
      {todos?.map(todo => (
        <li key={todo.id} style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>
          <input
            type="checkbox"
            checked={todo.completed}
            onChange={() => toggle.mutate({ id: todo.id, completed: !todo.completed })}
          />
          {todo.title}
        </li>
      ))}
    </ul>
  );
}

Module Quiz

Module Quiz
Question 1 of 5

What is a race condition in data fetching and how do you prevent it?

Tip

Tip

Practice Practice Quiz Data Fetching APIs in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Modern React: Use Hooks instead of class lifecycle methods

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz Data Fetching APIs from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Practice Quiz Data Fetching APIs is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done