What is @graphql-codegen/typescript-react-query?
@graphql-codegen/typescript-react-query is a plugin for GraphQL Code Generator that generates TypeScript types and React Query hooks from your GraphQL schema and operations. This allows you to seamlessly integrate GraphQL queries and mutations into your React applications using React Query, providing type safety and reducing boilerplate code.
What are @graphql-codegen/typescript-react-query's main functionalities?
Generate TypeScript Types
This configuration generates TypeScript types for your GraphQL schema and operations. The generated types ensure type safety when working with GraphQL queries and mutations in your React application.
```json
{
"schema": "https://my-graphql-endpoint.com/schema",
"documents": "src/graphql/**/*.graphql",
"generates": {
"src/generated/graphql.tsx": {
"plugins": [
"typescript",
"typescript-operations",
"typescript-react-query"
]
}
}
}
```
Generate React Query Hooks
This code sample demonstrates how to use the generated React Query hooks for fetching and mutating data. The `useGetUserQuery` hook is used to fetch user data, and the `useCreateUserMutation` hook is used to create a new user.
```typescript
import { useGetUserQuery, useCreateUserMutation } from './generated/graphql';
const UserComponent = () => {
const { data, error, isLoading } = useGetUserQuery({ id: '1' });
const mutation = useCreateUserMutation();
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>{data.user.name}</h1>
<button onClick={() => mutation.mutate({ name: 'New User' })}>Create User</button>
</div>
);
};
```
Other packages similar to @graphql-codegen/typescript-react-query
graphql-codegen-typescript
This package is part of the GraphQL Code Generator ecosystem and focuses on generating TypeScript types from your GraphQL schema. It does not generate React Query hooks but can be used in conjunction with other plugins to achieve similar functionality.
graphql-codegen-typescript-operations
This package generates TypeScript types for your GraphQL operations (queries, mutations, and subscriptions). It is often used alongside `graphql-codegen-typescript` to provide a complete type-safe GraphQL experience in TypeScript projects.
graphql-request
A minimal GraphQL client for making requests to a GraphQL server. While it does not generate TypeScript types or React Query hooks, it provides a simple and lightweight way to interact with GraphQL APIs.
urql
A highly customizable and versatile GraphQL client for React. It provides hooks for querying and mutating data, similar to React Query, but does not generate TypeScript types automatically.