website/src/pages/plugins/typescript/typescript-react-apollo.mdx
import { Callout } from '@theguild/components' import { PluginApiDocs, PluginHeader } from '@/components/plugin' import { pluginGetStaticProps } from '@/lib/plugin-get-static-props' export const getStaticProps = pluginGetStaticProps(__filename, { hasOperationsNote: true })
<Callout type="info">We now recommend using the client-preset package for a better developer experience and smaller impact on bundle size.
Get started on our "React/Vue" guide.
</Callout> <Callout type="warning">The generated hooks created by this package are no longer compatible with Apollo Client 4.0. We provide a codemod that automates the the migration to the client preset. See the tutorial video to learn how to use the codemod to migrate your codebase.
For the given input:
query Test {
feed {
id
commentCount
repository {
full_name
html_url
owner {
avatar_url
}
}
}
}
And the following configuration:
import type { CodegenConfig } from '@graphql-codegen/cli'
const config: CodegenConfig = {
schema: 'YOUR_SCHEMA_HERE',
documents: './src/**/*.graphql',
generates: {
'./generated-types.ts': {
plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo']
}
}
}
export default config
Codegen will pre-compile the GraphQL operation into a DocumentNode object, and generate a ready-to-use React Hook for each operation you have.
In your application code, you can import it from the generated file, and use the React Hook in your component code:
import { useTest } from './generated-types'
export const MyComponent: React.FC = () => {
const { data, error, loading } = useTest()
return <div>…</div>
}
Codegen also supports generating data Components (deprecated in @apollo/client v3), you can turn it on this way:
import type { CodegenConfig } from '@graphql-codegen/cli'
const config: CodegenConfig = {
schema: 'YOUR_SCHEMA_HERE',
documents: './src/**/*.graphql',
generates: {
'./generated-types.ts': {
plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'],
config: {
withComponent: true
}
}
}
}
export default config
Codegen also supports generating High-Order-Components (deprecated in @apollo/client v3), you can turn it on this way:
import type { CodegenConfig } from '@graphql-codegen/cli'
const config: CodegenConfig = {
schema: 'YOUR_SCHEMA_HERE',
documents: './src/**/*.graphql',
generates: {
'./generated-types.ts': {
plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'],
config: {
withHOC: true
}
}
}
}
export default config