urql
БесплатноБез исполняемых скриптовНе проверенurql is a small, extensible GraphQL client for React, Preact, Vue, Svelte, Solid and plain JavaScript that sends queries, mutations and subscriptions and…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
urql — Lightweight GraphQL Client
Overview
urql is a GraphQL client built from a small core (@urql/core) and a pipeline of "exchanges" — middleware that each operation passes through, such as caching, auth, retries and the HTTP fetch itself. The default document cache stores whole query results and is enough for content-driven apps; @urql/exchange-graphcache adds a normalized cache when several queries must stay in sync after a mutation. The urql package holds the React bindings; @urql/preact, @urql/vue, @urql/svelte and @urql/solid wrap the same core.
Instructions
Installation
npm install urql graphql # React bindings + core (graphql is an optional peer dependency)
npm install @urql/exchange-graphcache # Optional normalized cache
npm install @urql/exchange-auth @urql/exchange-retry graphql-ws # Optional: auth, retries, subscriptions
Setup and Queries
import { Client, Provider, cacheExchange, fetchExchange, gql, useQuery, useMutation } from "urql";
const client = new Client({
url: "https://api.northwind.dev/graphql",
exchanges: [cacheExchange, fetchExchange], // required; order matters
fetchOptions: () => ({
headers: { Authorization: `Bearer ${getToken()}` },
}),
});
function App() {
return <Provider value={client}><Dashboard /></Provider>;
}
type Post = { id: string; title: string; createdAt: string; author: { id: string; name: string } };
// Type arguments give typed `data` and `variables` in the hooks
const POSTS_QUERY = gql<{ posts: Post[] }, { limit: number }>`
query Posts($limit: Int!) {
posts(limit: $limit) { id title author { id name } createdAt }
}
`;
function PostList() {
const [result, reexecute] = useQuery({
query: POSTS_QUERY,
variables: { limit: 10 },
});
const { data, fetching, error } = result;
if (fetching) return <Spinner />;
if (error) return <ErrorBanner message={error.message} />;
return (
<div>
{data?.posts.map(p => <PostCard key={p.id} post={p} />)}
<button onClick={() => reexecute({ requestPolicy: "network-only" })}>Refresh</button>
</div>
);
}
Since @urql/core 6 (urql 5), queries are sent as HTTP GET when the query string plus variables is under 2048 characters. If the server only accepts POST, add preferGetMethod: false to the Client options. Mutations always use POST.
Mutations
const CREATE_POST = gql`
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) { id title createdAt author { id name } }
}
`;
function CreatePostForm() {
const [result, createPost] = useMutation(CREATE_POST);
const handleSubmit = (input: { title: string }) => {
// The promise never rejects — check result.error instead of try/catch
createPost({ input }).then(result => {
if (result.error) console.error(result.error);
});
};
return <PostForm onSubmit={handleSubmit} loading={result.fetching} />;
}
Graphcache (Normalized Cache)
import { cacheExchange } from "@urql/exchange-graphcache";
// Replaces the default cacheExchange in the exchanges array
const cache = cacheExchange({
// Types are keyed by `id` or `_id` automatically; configure others here
keys: { PostStats: () => null }, // null = embedded, not a separate entity
resolvers: {
Query: {
// Serve Query.post(id) from a Post already cached by the list query
post: (_, args) => ({ __typename: "Post", id: args.id }),
},
},
updates: {
Mutation: {
// New entities are not added to lists automatically
createPost(result, _args, cache) {
cache.updateQuery({ query: POSTS_QUERY, variables: { limit: 10 } }, (data) => {
if (data) data.posts.unshift(result.createPost as Post);
return data;
});
},
deletePost(_result, args, cache) {
cache.invalidate({ __typename: "Post", id: args.id as string });
},
},
},
});
Auth, Retry and Subscriptions
import { Client, cacheExchange, fetchExchange, subscriptionExchange } from "urql";
import { authExchange } from "@urql/exchange-auth";
import { retryExchange } from "@urql/exchange-retry";
import { createClient as createWSClient } from "graphql-ws";
const wsClient = createWSClient({ url: "wss://api.northwind.dev/graphql" });
const client = new Client({
url: "https://api.northwind.dev/graphql",
exchanges: [
cacheExchange, // synchronous exchanges first
authExchange(async (utils) => {
let token = localStorage.getItem("token");
return {
addAuthToOperation: (operation) =>
token ? utils.appendHeaders(operation, { Authorization: `Bearer ${token}` }) : operation,
didAuthError: (error) => error.graphQLErrors.some(e => e.extensions?.code === "UNAUTHENTICATED"),
refreshAuth: async () => {
token = await refreshSession(); // runs once; failed operations are
Установить urql в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл urql?
urql is a small, extensible GraphQL client for React, Preact, Vue, Svelte, Solid and plain JavaScript that sends queries, mutations and subscriptions and caches the results. Use when a user asks to add a GraphQL client to a frontend, fetch data with useQuery or useMutation, set up normalized caching with Graphcache, add auth, retry or subscription exchanges, replace Apollo Client with something lighter, or upgrade to urql 5.
Как установить скилл urql?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл urql запускает скрипты?
Нет, скилл состоит только из инструкций (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