Certainly! Below is a step-by-step guide to creating a seamless optimistic addition of new elements to the list using React, TypeScript, and TanStack Router (formerly React Router). This implementation will allow users to click on the newly added item to see its details even before receiving the actual response from the server. If the server response fails, the changes will be reverted, and the user will be redirected back.
Step 1: Set Up the Project
First, ensure you have a React project set up with TypeScript. If you don't already have a project, you can create one using Create React App:
npx create-react-app optimistic-update --template typescript
cd optimistic-update
Next, install the necessary dependencies:
npm install @tanstack/react-router @tanstack/react-query
Step 2: Set Up TanStack Router
Create a router.tsx file to configure your routes.
// src/router.tsx
import { createRouter } from '@tanstack/react-router';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactNode } from 'react';
import { ItemList } from './components/ItemList';
import { ItemDetails } from './components/ItemDetails';
import { AddItemForm } from './components/AddItemForm';
const queryClient = new QueryClient();
const router = createRouter({
routeTree: (
<root>
<index component={ItemList} />
<item id="itemId" component={ItemDetails} />
<add component={AddItemForm} />
</root>
),
});
declare module '@tanstack/react-router' {
interface Register {
router: typeof router;
}
}
export function RouterProviders({ children }: { children: ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
{router.provideComponent({ children })}
</QueryClientProvider>
);
}
export default router;
Step 3: Create the Item Interface and API Service
Create an api.ts file to mock the API service.
// src/api.ts
export interface Item {
id: string;
name: string;
}
export const addItem = async (item: Omit<Item, 'id'>): Promise<Item> => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ id: Math.random().toString(36).substr(2, 9), ...item });
}, 1000);
});
};
export const fetchItems = async (): Promise<Item[]> => {
return new Promise((resolve) => {
setTimeout(() => {
resolve([
{ id: '1', name: 'Item 1' },
{ id: '2', name: 'Item 2' },
]);
}, 1000);
});
};
export const fetchItemDetails = async (id: string): Promise<Item> => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ id, name: `Details for Item ${id}` });
}, 1000);
});
};
Step 4: Create the Item List Component
// src/components/ItemList.tsx
import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { Link, useNavigate } from '@tanstack/react-router';
import { fetchItems, Item } from '../api';
export const ItemList: React.FC = () => {
const { data: items = [] } = useQuery<Item[]>({
queryKey: ['items'],
queryFn: fetchItems,
});
const navigate = useNavigate();
return (
<div>
<h1>Item List</h1>
<ul>
{items.map((item) => (
<li key={item.id}>
<Link to="/item/$itemId" params={{ itemId: item.id }}>
{item.name}
</Link>
</li>
))}
</ul>
<button onClick={() => navigate({ to: '/add' })}>Add Item</button>
</div>
);
};
Step 5: Create the Item Details Component
// src/components/ItemDetails.tsx
import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { useParams } from '@tanstack/react-router';
import { fetchItemDetails, Item } from '../api';
export const ItemDetails: React.FC = () => {
const { itemId } = useParams({ from: '/item/$itemId' });
const { data: item } = useQuery<Item>({
queryKey: ['item', itemId],
queryFn: () => fetchItemDetails(itemId!),
enabled!!itemId,
});
if (!item) return <div>Loading...</div>;
return (
<div>
<h1>{item.name}</h1>
<p>Details for item {item.id}</p>
</div>
);
};
Step 6: Create the Add Item Form Component
// src/components/AddItemForm.tsx
import React, { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from '@tanstack/react-router';
import { addItem, Item } from '../api';
export const AddItemForm: React.FC = () => {
const [name, setName] = useState<string>('');
const queryClient = useQueryClient();
const navigate = useNavigate();
const mutation = useMutation<Item, Error, { name: string }>({
mutationFn: ({ name }) => addItem({ name }),
onMutate: async (newItem) => {
await queryClient.cancelQueries({ queryKey: ['items'] });
const previousItems = queryClient.getQueryData<Item[]>(['items']);
queryClient.setQueryData<Item[]>(['items'], (old) => [
...(old || []),
{ id: 'optimistic-' + Math.random().toString(36).substr(2, 9), name: newItem.name },
]);
return { previousItems };
},
onError: (_err, _newItem, context) => {
queryClient.setQueryData(['items'], context?.previousItems);
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ['items'] });
},
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
mutation.mutate({ name }, {
onSuccess: (newItem) => {
navigate({ to: `/item/$itemId`, params: { itemId: newItem.id } });
},
onError: () => {
navigate({ to: '/' });
},
});
setName('');
};
return (
<div>
<h1>Add Item</h1>
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Item name"
/>
<button type="submit" disabled={mutation.isLoading}>
{mutation.isLoading ? 'Adding...' : 'Add Item'}
</button>
</form>
</div>
);
};
Step 7: Update the App Component
Finally, update your App.tsx to include the RouterProviders and the router.
// src/App.tsx
import React from 'react';
import { RouterProviders } from './router';
const App: React.FC = () => {
return (
<RouterProviders>
<main>
<RouterProviders.Outlet />
</main>
</RouterProviders>
);
};
export default App;
Explanation
-
Router Setup: The router.tsx file sets up the routes for the item list, item details, and add item form using TanStack Router.
-
API Service: The api.ts file contains mock API functions for adding, fetching items, and fetching item details.
-
ItemList Component: Displays the list of items and allows navigation to the add item form.
-
ItemDetails Component: Fetches and displays details for a specific item.
-
AddItemForm Component:
- Uses the
useMutation hook from TanStack Query to handle the addition of new items.
- onMutate: Optimistically updates the item list by adding the new item with a temporary ID.
- onError: Reverts the optimistic update if the mutation fails.
- onSettled: Refetches the item list to ensure it is up-to-date after the mutation.
- onSuccess: Navigates to the details page of the newly added item.
- onError: Navigates back to the item list if the mutation fails.
-
App Component: Wraps the application with the RouterProviders to provide the necessary routing and query client context.
With this setup you will have a seamless optimistic update for adding new items, with the ability to navigate to the item details page immediately, and handle errors by reverting changes and navigating back.