data-fetching
БесплатноБез исполняемых скриптовНе проверенData fetching with TanStack Query, loading states, and error handling
Об этом скилле
Data Fetching Patterns
1. Basic Query with TanStack Query
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
interface User {
id: string;
name: string;
email: string;
}
// API functions
async function fetchUser(userId: string): Promise<User> {
const res = await fetch(`/api/users/${userId}`);
if (!res.ok) throw new Error("Failed to fetch user");
return res.json();
}
async function updateUser(user: Partial<User> & { id: string }): Promise<User> {
const res = await fetch(`/api/users/${user.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(user),
});
if (!res.ok) throw new Error("Failed to update user");
return res.json();
}
// Component
function UserProfile({ userId }: { userId: string }) {
const { data: user, isLoading, error } = useQuery({
queryKey: ["user", userId],
queryFn: () => fetchUser(userId),
});
if (isLoading) return <UserSkeleton />;
if (error) return <ErrorMessage error={error} />;
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
}
2. Mutations with Optimistic Updates
function UserEditor({ userId }: { userId: string }) {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: updateUser,
// Optimistic update
onMutate: async (newUser) => {
// Cancel outgoing refetches
await queryClient.cancelQueries({ queryKey: ["user", userId] });
// Snapshot previous value
const previousUser = queryClient.getQueryData<User>(["user", userId]);
// Optimistically update
queryClient.setQueryData<User>(["user", userId], (old) => ({
...old!,
...newUser,
}));
return { previousUser };
},
// Rollback on error
onError: (err, newUser, context) => {
queryClient.setQueryData(["user", userId], context?.previousUser);
},
// Always refetch after error or success
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["user", userId] });
},
});
return (
<form onSubmit={(e) => {
e.preventDefault();
mutation.mutate({ id: userId, name: "New Name" });
}}>
<button disabled={mutation.isPending}>
{mutation.isPending ? "Saving..." : "Save"}
</button>
{mutation.isError && <p>Error: {mutation.error.message}</p>}
</form>
);
}
3. Infinite Scroll / Pagination
import { useInfiniteQuery } from "@tanstack/react-query";
interface Page {
items: Item[];
nextCursor?: string;
}
function InfiniteList() {
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ["items"],
queryFn: ({ pageParam }) => fetchItems(pageParam),
initialPageParam: undefined as string | undefined,
getNextPageParam: (lastPage) => lastPage.nextCursor,
});
const items = data?.pages.flatMap((page) => page.items) ?? [];
return (
<div>
{items.map((item) => (
<ItemCard key={item.id} item={item} />
))}
{hasNextPage && (
<button
onClick={() => fetchNextPage()}
disabled={isFetchingNextPage}
>
{isFetchingNextPage ? "Loading..." : "Load More"}
</button>
)}
</div>
);
}
4. Dependent Queries
function UserPosts({ userId }: { userId: string }) {
// First query
const { data: user } = useQuery({
queryKey: ["user", userId],
queryFn: () => fetchUser(userId),
});
// Dependent query - only runs when user is available
const { data: posts } = useQuery({
queryKey: ["posts", user?.id],
queryFn: () => fetchUserPosts(user!.id),
enabled: !!user, // Only run when user exists
});
return (
<div>
<h1>{user?.name}'s Posts</h1>
{posts?.map((post) => <PostCard key={post.id} post={post} />)}
</div>
);
}
5. Prefetching
function UserList() {
const queryClient = useQueryClient();
return (
<ul>
{users.map((user) => (
<li
key={user.id}
// Prefetch on hover
onMouseEnter={() => {
queryClient.prefetchQuery({
queryKey: ["user", user.id],
queryFn: () => fetchUser(user.id),
staleTime: 5 * 60 * 1000, // 5 minutes
});
}}
>
<Link href={`/users/${user.id}`}>{user.name}</Link>
</li>
))}
</ul>
);
}
6. Loading & Error States
// Skeleton component
function UserSkeleton() {
return (
<div className="animate-pulse">
<div className="h-8 w-48 bg-muted rounded" />
<div className="h-4 w-32 bg-muted rounded mt-2" />
</div>
);
}
// Error component with retry
function ErrorMessage({ error, retry }: { error: Error; retry?: () => void }) {
return (
<div className="rounded-md bg-red-50 p-4">
<div className="flex">
<AlertCircle classNam
Установить data-fetching в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл data-fetching?
Data fetching with TanStack Query, loading states, and error handling
Как установить скилл data-fetching?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл data-fetching запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic