@arraypress/query-keys
v1.0.0
Published
TanStack Query key factory for consistent cache key patterns. Generates .all, .list(params), and .detail(id) keys for any resource.
Maintainers
Readme
@arraypress/query-keys
TanStack Query key factory for consistent cache key patterns. Generates .all, .list(params), and .detail(id) keys for any resource.
Zero dependencies. Works in Node.js, Cloudflare Workers, Deno, Bun, and browsers.
Installation
npm install @arraypress/query-keysUsage
import { createQueryKeys, createQueryKeyMap } from '@arraypress/query-keys';
// Single resource
const products = createQueryKeys('products');
products.all; // ['products']
products.list({ page: 1 }); // ['products', 'list', { page: 1 }]
products.detail(42); // ['products', 'detail', 42]
// Multiple resources at once
const keys = createQueryKeyMap(['products', 'orders', 'customers']);
keys.products.detail(1); // ['products', 'detail', 1]
keys.orders.list({ status: 'pending' }); // ['orders', 'list', { status: 'pending' }]
keys.customers.all; // ['customers']With TanStack Query
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { createQueryKeys } from '@arraypress/query-keys';
const keys = createQueryKeys('products');
// Fetch a list
const { data } = useQuery({
queryKey: keys.list({ page: 1 }),
queryFn: () => fetch('/api/products?page=1').then(r => r.json()),
});
// Fetch a single item
const { data: product } = useQuery({
queryKey: keys.detail(42),
queryFn: () => fetch('/api/products/42').then(r => r.json()),
});
// Invalidate all product queries (lists + details)
const queryClient = useQueryClient();
queryClient.invalidateQueries({ queryKey: keys.all });API
createQueryKeys(resource): QueryKeySet
Create a query key factory for a single resource.
Returns an object with:
.all--[resource]-- matches all queries for this resource (useful for broad invalidation).list(params?)--[resource, 'list']or[resource, 'list', params]-- for list/search queries.detail(id)--[resource, 'detail', id]-- for single-item queries
createQueryKeyMap(resources): Record<string, QueryKeySet>
Create query key factories for multiple resources at once. Takes an array of resource names and returns an object keyed by resource name.
Key Hierarchy
Keys are structured so that invalidating a parent key also invalidates children:
['products'] <- invalidates everything
['products', 'list'] <- invalidates all lists
['products', 'list', { page: 1 }] <- invalidates one specific list
['products', 'detail', 42] <- invalidates one specific itemLicense
MIT
