react + ts + tanstack. We have list of items, and form for adding new items, and we can…
- User
react + ts + tanstack. We have list of items, and form for adding new items, and we can click on item and see page with its details. Create the best way of seamless optimistic addition of new element to the list, with ability click on it to see details, even before actual respose from the server, but revert changes and redirect back if something will go wrong
Assistant
Here's a comprehensive solution for optimistic updates with seamless navigation using React + TypeScript + TanStack Query:
Types and Setup
// types.ts export interface Item { id: string; title: string; description: string; createdAt: string; } export interface CreateItemData { title: string; description: string; } export interface OptimisticItem extends Item { isOptimistic?: boolean; tempId?: string; }API Layer
// api.ts export const itemsApi = { getItems: async (): Promise<Item[]> => { const response = await fetch('/api/items'); if (!response.ok) throw new Error('Failed to fetch items'); return response.json(); }, getItem: async (id: string): Promise<Item> => { const response = await fetch(`/api/items/${id}`); if (!response.ok) throw new Error('Failed to fetch item'); return response.json(); }, createItem: async (data: CreateItemData): Promise<Item> => { const response = await fetch('/api/items', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }); if (!response.ok) throw new Error('Failed to create item'); return response.json(); }, };Custom Hook for Optimistic Updates
// hooks/useOptimisticItems.ts import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useNavigate } from 'react-router-dom'; import { itemsApi } from '../api'; import { CreateItemData, Item, OptimisticItem } from '../types'; const ITEMS_QUERY_KEY = ['items']; export const useOptimisticItems = () => { const queryClient = useQueryClient(); const navigate = useNavigate(); const itemsQuery = useQuery({ queryKey: ITEMS_QUERY_KEY, queryFn: itemsApi.getItems, }); const createItemMutation = useMutation({ mutationFn: itemsApi.createItem, onMutate: async (newItemData: CreateItemData) => { // Cancel outgoing refetches await queryClient.cancelQueries({ queryKey: ITEMS_QUERY_KEY }); // Snapshot previous value const previousItems = queryClient.getQueryData<Item[]>(ITEMS_QUERY_KEY); // Create optimistic item with temporary ID const tempId = `temp-${Date.now()}-${Math.random()}`; const optimisticItem: OptimisticItem = { id: tempId, tempId, title: newItemData.title, description: newItemData.description, createdAt: new Date().toISOString(), isOptimistic: true, }; // Optimistically update the cache queryClient.setQueryData<Item[]>(ITEMS_QUERY_KEY, (old = []) => [ optimisticItem, ...old, ]); // Store optimistic item separately for detail page access queryClient.setQueryData(['item', tempId], optimisticItem); return { previousItems, tempId, optimisticItem }; }, onSuccess: (newItem, variables, context) => { if (context) { // Remove optimistic item data queryClient.removeQueries({ queryKey: ['item', context.tempId] }); // Update the real item data queryClient.setQueryData(['item', newItem.id], newItem); // Update items list with real item queryClient.setQueryData<Item[]>(ITEMS_QUERY_KEY, (old = []) => old.map(item => 'tempId' in item && item.tempId === context.tempId ? newItem : item ) ); // Check if user is currently viewing the optimistic item and redirect if (window.location.pathname === `/items/${context.tempId}`) { navigate(`/items/${newItem.id}`, { replace: true }); } } }, onError: (error, variables, context) => { // Revert optimistic update if (context) { queryClient.setQueryData(ITEMS_QUERY_KEY, context.previousItems); queryClient.removeQueries({ queryKey: ['item', context.tempId] }); // If user is viewing the failed optimistic item, redirect back if (window.location.pathname === `/items/${context.tempId}`) { navigate('/items', { replace: true }); } } }, onSettled: () => { // Refetch to ensure we have the latest data queryClient.invalidateQueries({ queryKey: ITEMS_QUERY_KEY }); }, }); return { items: itemsQuery.data ?? [], isLoading: itemsQuery.isLoading, createItem: createItemMutation.mutate, isCreating: createItemMutation.isPending, }; };Hook for Item Details
// hooks/useItemDetails.ts import { useQuery } from '@tanstack/react-query'; import { itemsApi } from '../api'; import { OptimisticItem } from '../types'; export const useItemDetails = (id: string) => { return useQuery({ queryKey: ['item', id], queryFn: async () => { // First check if this is an optimistic item already in cache const optimisticItem = useQuery.getQueryData<OptimisticItem>(['item', id]); if (optimisticItem?.isOptimistic) { return optimisticItem; } // Otherwise fetch from server return itemsApi.getItem(id); }, staleTime: 1000 * 60 * 5, // 5 minutes }); };Components
// components/ItemsList.tsx import React from 'react'; import { Link } from 'react-router-dom'; import { useOptimisticItems } from '../hooks/useOptimisticItems'; import { OptimisticItem } from '../types'; export const ItemsList: React.FC = () => { const { items, isLoading } = useOptimisticItems(); if (isLoading) return <div>Loading...</div>; return ( <div className="space-y-4"> <h1 className="text-2xl font-bold">Items</h1> <div className="grid gap-4"> {items.map((item) => ( <ItemCard key={item.id} item={item} /> ))} </div> </div> ); }; const ItemCard: React.FC<{ item: OptimisticItem }> = ({ item }) => { return ( <Link to={`/items/${item.id}`} className={`block p-4 border rounded-lg hover:shadow-md transition-shadow ${ item.isOptimistic ? 'border-blue-300 bg-blue-50 opacity-75' : 'border-gray-300 bg-white' }`} > <h3 className="font-semibold"> {item.title} {item.isOptimistic && ( <span className="ml-2 text-xs text-blue-600">(Saving...)</span> )} </h3> <p className="text-gray-600 mt-1">{item.description}</p> </Link> ); };// components/AddItemForm.tsx import React, { useState } from 'react'; import { useOptimisticItems } from '../hooks/useOptimisticItems'; export const AddItemForm: React.FC = () => { const [title, setTitle] = useState(''); const [description, setDescription] = useState(''); const { createItem, isCreating } = useOptimisticItems(); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (title.trim() && description.trim()) { createItem({ title: title.trim(), description: description.trim() }); setTitle(''); setDescription(''); } }; return ( <form onSubmit={handleSubmit} className="space-y-4 p-4 border rounded-lg"> <h2 className="text-xl font-semibold">Add New Item</h2> <input type="text" placeholder="Title" value={title} onChange={(e) => setTitle(e.target.value)} className="w-full p-2 border rounded" disabled={isCreating} /> <textarea placeholder="Description" value={description} onChange={(e) => setDescription(e.target.value)} className="w-full p-2 border rounded h-24" disabled={isCreating} /> <button type="submit" disabled={isCreating || !title.trim() || !description.trim()} className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50" > {isCreating ? 'Adding...' : 'Add Item'} </button> </form> ); };// components/ItemDetails.tsx import React from 'react'; import { useParams, useNavigate } from 'react-router-dom'; import { useItemDetails } from '../hooks/useItemDetails'; import { OptimisticItem } from '../types'; export const ItemDetails: React.FC = () => { const { id } = useParams<{ id: string }>(); const navigate = useNavigate(); const { data: item, isLoading, error } = useItemDetails(id!); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error loading item</div>; if (!item) return <div>Item not found</div>; const optimisticItem = item as OptimisticItem; return ( <div className="max-w-2xl mx-auto p-6"> <button onClick={() => navigate('/items')} className="mb-4 text-blue-500 hover:text-blue-700" > ← Back to Items </button> <div className={`${optimisticItem.isOptimistic ? 'opacity-75' : ''}`}> <h1 className="text-3xl font-bold mb-4"> {item.title} {optimisticItem.isOptimistic && ( <span className="ml-3 text-lg text-blue-600 font-normal"> (Saving...) </span> )} </h1> <p className="text-gray-700 mb-4">{item.description}</p> <p className="text-sm text-gray-500"> Created: {new Date(item.createdAt).toLocaleDateString()} </p> </div> </div> ); };App Setup
// App.tsx import React from 'react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; import { ItemsList } from './components/ItemsList'; import { ItemDetails } from './components/ItemDetails'; import { AddItemForm } from './components/AddItemForm'; const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 1000 * 60 * 5, // 5 minutes retry: (failureCount, error) => { // Don't retry for optimistic items that fail return failureCount < 3; }, }, }, }); export const App: React.FC = () => { return ( <QueryClientProvider client={queryClient}> <Router> <div className="min-h-screen bg-gray-50 p-8"> <Routes> <Route path="/items" element={ <div className="max-w-4xl mx-auto space-y-8"> <AddItemForm /> <ItemsList /> </div> } /> <Route path="/items/:id" element={<ItemDetails />} /> <Route path="/" element={<Navigate to="/items" replace />} /> </Routes> </div> </Router> </QueryClientProvider> ); };Key Features
This solution provides:
- Seamless Optimistic Updates: New items appear instantly in the list with visual feedback
- Clickable Optimistic Items: Users can navigate to detail pages of items that haven't been saved yet
- Automatic Rollback: Failed requests revert the UI and redirect users appropriately
- Visual Feedback: Optimistic items are styled differently to indicate their temporary state
- Proper Navigation: URLs update correctly when optimistic items are confirmed by the server
- Error Handling: Comprehensive error handling with user-friendly fallbacks
The system handles all edge cases including network failures, navigation during pending requests, and proper cleanup of temporary data.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.