Schema-First Validation
Quantum Query treats data integrity as a first-class citizen. Unlike other libraries where validation is an afterthought handled manually in hooks, Quantum Query integrates validation directly into the fetch/cache cycle.
Why Validate at the Edge?
- Type Safety: Ensure the data in your cache matches your TypeScript interfaces.
- Graceful Failure: Catch API contract breakages before they crash your UI.
- Sanitization: Strip out unexpected properties from large API responses.
Using with Zod
We recommend Zod for schema definition, but any library with a .parse() method will work.
import { z } from 'zod';
import { useQuery } from '@braine/quantum-query';
const UserSchema = z.object({
id: z.number(),
username: z.string(),
email: z.string().email(),
});
type User = z.infer<typeof UserSchema>;
function UserProfile({ id }) {
const { data } = useQuery({
queryKey: ['user', id],
queryFn: () => fetch(`/api/users/${id}`).then(res => res.json()),
// Integrated Validation
schema: UserSchema,
});
return <div>{data?.username}</div>;
}
Global Validation
You can define a default schema for your entire QueryClient. This is useful for standard API envelopes.
const client = new QueryClient({
defaultSchema: GlobalResponseSchema,
});
How it Works
When a schema is provided:
- The
QueryRemoteslayer fetches the raw data. - The
QueryClientrunsschema.parse(data)before updating the storage. - If validation fails, the query enters an
errorstate with aZodError, preventing corrupted data from entering your application state.