{"id":20801163,"url":"https://github.com/pothos-dev/apollo-hooks-codegen","last_synced_at":"2025-10-20T05:03:44.086Z","repository":{"id":129130581,"uuid":"160078949","full_name":"pothos-dev/apollo-hooks-codegen","owner":"pothos-dev","description":"A plugin for graphql-code-generator to create fully typed React Hooks from GraphQL queries, mutations and subscriptions.","archived":false,"fork":false,"pushed_at":"2020-05-18T06:58:59.000Z","size":627,"stargazers_count":46,"open_issues_count":5,"forks_count":4,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-06-06T21:03:41.549Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pothos-dev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2018-12-02T18:53:13.000Z","updated_at":"2023-09-10T15:01:45.000Z","dependencies_parsed_at":"2023-03-20T10:34:54.546Z","dependency_job_id":null,"html_url":"https://github.com/pothos-dev/apollo-hooks-codegen","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/pothos-dev/apollo-hooks-codegen","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pothos-dev%2Fapollo-hooks-codegen","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pothos-dev%2Fapollo-hooks-codegen/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pothos-dev%2Fapollo-hooks-codegen/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pothos-dev%2Fapollo-hooks-codegen/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pothos-dev","download_url":"https://codeload.github.com/pothos-dev/apollo-hooks-codegen/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pothos-dev%2Fapollo-hooks-codegen/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":273555459,"owners_count":25126316,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-04T02:00:08.968Z","response_time":61,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-17T18:16:54.045Z","updated_at":"2025-10-20T05:03:43.996Z","avatar_url":"https://github.com/pothos-dev.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"This is a plugin for [graphql-code-generator](https://github.com/dotansimha/graphql-code-generator) that generates fully typed React Hooks from queries, mutations and subscriptions in `.graphql` files.\n\n## Getting started\n\n### Installation\n\n`npm i -D graphql-code-generator apollo-hooks-codegen`\n\n### Writing Queries\n\nUnless traditional Apollo usage, we're actually writing all our queries, mutations and subscriptions inside a dedicated .graphql file:\n\n```graphql\n# /src/graphql/todos.graphql\nfragment TodoParts on TodoItem {\n  id\n  title\n  isDone\n}\n\nquery getAllTodos {\n  todoItems {\n    ...TodoParts\n  }\n}\n\nsubscription subscribeTodos {\n  newTodoItem: subscribeTodoItems {\n    ...TodoParts\n  }\n}\n\nmutation createTodo($todoItem: TodoItemInput!) {\n  createTodoItem(todoItem: $todoItem) {\n    id\n  }\n}\n```\n\n### Setting up codegen\n\nThe graphql-code-generator is best configured via a [codegen.yml file](https://graphql-code-generator.com/docs/getting-started/codegen-config).\n\nHere we tell the generator to create a _./src/graphql/index.ts_ file using apollo-hooks-codegen.\n\n```yml\n# codegen.yml\nschema: http://localhost:4000\ndocuments: ./src/graphql/*.graphql\noverwrite: true\ngenerates:\n  ./src/graphql/index.ts:\n    - apollo-hooks-codegen\n```\n\nAfter creating the file, we just run:\n`npx gql-gen`\n\n### Configuring ApolloClient\n\nThe hooks need access to an instance of [ApolloClient](https://www.apollographql.com/docs/react/api/apollo-client.html). If you previously used Apollo, you probably already have this set up, otherwise, refer to the [Get started](https://www.apollographql.com/docs/react/essentials/get-started.html) guide.\n\nThe code generator created an ApolloHooksProvider, which we have to set up at the root of our app:\n\n```tsx\nimport { ApolloHooksProvider } from './src/graphql'\n\nconst apolloClient = new ApolloClient({\n  /* ApolloClient configuration here */\n})\n\nfunction AppWithApollo() {\n  return (\n    \u003cApolloHooksProvider apolloClient={apolloClient}\u003e\n      \u003cApp /\u003e\n    \u003c/ApolloHooksProvider\u003e\n  )\n}\n```\n\nAfter all of this is done, we can now start using the generated hooks.\n\n## Usage\n\nEvery document (`query`, `mutation`, `subscription` or `fragment`) in the .graphql file generated a Typescript function of the same name.\n\nEach function takes an optional argument, which contains additional options. The configured document is then passed to one of the provided hooks:\n\n### Queries\n\nuseQuery uses [watchQuery](https://www.apollographql.com/docs/react/api/apollo-client.html#ApolloClient.watchQuery) under the hood, so the component will re-render automatically if the queried data changes in Apollo's cache for any reason.\n\n```tsx\nimport { useQuery, getAllTodos } from './src/graphql'\n\nfunction TodoList() {\n  const queryResult = useQuery(getAllTodos({ fetchPolicy: 'cache-first' }))\n\n  // get access to loading and error state of the query\n  if (queryResult.loading) return \u003cp\u003eLoading...\u003c/p\u003e\n  if (queryResult.error) return \u003cp\u003eError\u003c/p\u003e\n\n  // data is null during loading and in case of error, but can be expected to be non-null otherwise\n  const todoItems = queryResult.data!.todoItems\n\n  // the compiler knows about which fields are available on todoItems\n  return (\n    \u003cul\u003e\n      {todoItems.map(item =\u003e (\n        \u003cli key={item.id}\u003e{item.title}\u003c/li\u003e\n      ))}\n    \u003c/ul\u003e\n  )\n}\n```\n\n### Mutations\n\nuseMutation creates a function which executes the configured mutation and returns the result as a Promise.\n\n```tsx\nimport { useMutation, createTodo } from './src/graphql'\n\nfunction AddTodoButton() {\n  const mutate = useMutation(\n    createTodo({\n      // options can be passed directly during configuration, like with useQuery.\n      // alternatively, you can pass the options object later when calling the mutate function\n      variables: {\n        todoItem: { title: 'Finish this button component...' },\n      },\n    })\n  )\n\n  return (\n    \u003cbutton\n      onClick={() =\u003e {\n        mutate().then(console.log)\n      }}\n    \u003e\n      Click me!\n    \u003c/button\u003e\n  )\n}\n```\n\n### Subscriptions\n\nSubscriptions require additional work when setting up ApolloClient, see [here](https://www.apollographql.com/docs/react/advanced/subscriptions.html#subscriptions-client).\n\n```tsx\nimport { useSubscription, subscribeTodos } from './src/graphql'\n\nfunction TodoItemTicker() {\n  const sub = useSubscription(subscribeTodos())\n\n  // If we did not receive a subscription event yet, the value is null\n  if (sub == null) return null\n\n  return \u003cp\u003eLatest Todo: {sub.newTodoItem.title}\u003c/p\u003e\n}\n```\n\nOften, you want to send a query to get some data, and create a subscription to be called back whenever the data changes on server. You can use this helper function to do both in one:\n\n```tsx\nimport { useQuery, getAllTodos } from './src/graphql'\n\nfunction TodoList() {\n  const queryResult = useQueryWithSubscription(\n    getAllTodos(), // the initial query\n    subscribeTodos(), // the subscription\n    (queryData, subData) =\u003e ({\n      // Update the query data here with the latest data from the subscription\n      todoItems: [...queryData.todoItems, subData.newTodoItem],\n    })\n  )\n\n  // loading and error state are taken only from the query\n  if (queryResult.loading) return \u003cp\u003eLoading...\u003c/p\u003e\n  if (queryResult.error) return \u003cp\u003eError\u003c/p\u003e\n\n  const todoItems = queryResult.data!.todoItems\n\n  return (\n    \u003cul\u003e\n      {todoItems.map(item =\u003e (\n        \u003cli key={item.id}\u003e{item.title}\u003c/li\u003e\n      ))}\n    \u003c/ul\u003e\n  )\n}\n```\n\n## Types\n\nA key feature of GraphQL is the possibility to fetch as many or as few properties of an object as is needed for a particular view. For this reason, it is difficult to assume a specific interface for any GraphQL type.\n\nThis library generates named interfaces for every selection of fields in a query. For example, given the above mutation:\n\n```graphql\nmutation createTodo($todoItem: TodoItemInput!) {\n  createTodoItem(todoItem: $todoItem) {\n    id\n  }\n}\n```\n\nthe following types are generated:\n\n```ts\n// TodoItemInput\ntype TodoItemInput = {\n  title: TodoItemInput_title\n  description?: Nullable\u003cTodoItemInput_description\u003e\n  dueDate?: Nullable\u003cTodoItemInput_dueDate\u003e\n}\ntype TodoItemInput_title = string\ntype TodoItemInput_description = string\ntype TodoItemInput_dueDate = any\n\n// createTodo() mutation\ntype createTodo_variables = {\n  todoItem: createTodo_variables_todoItem\n}\ntype createTodo_variables_todoItem = TodoItemInput\ntype createTodo_data = {\n  createTodoItem: createTodo_data_createTodoItem\n}\ntype createTodo_data_createTodoItem = { id: createTodo_data_createTodoItem_id }\ntype createTodo_data_createTodoItem_id = string\n```\n\nSo it is easy to specify the type of the variables or result (data) of a query or mutation, or any subselection of those.\n\nIf you want to re-use a type, I suggest to use named fragments, which create types of the same name as the fragment:\n\n```graphql\nfragment TodoParts on TodoItem {\n  id\n  title\n  isDone\n}\n```\n\nproduces:\n\n```ts\ntype TodoParts = {\n  id: TodoParts_id\n  title: TodoParts_title\n  isDone: TodoParts_isDone\n}\ntype TodoParts_id = string\ntype TodoParts_title = string\ntype TodoParts_isDone = boolean\n```\n\n## Generator Options\n\nYou can specify some options in the codegen.yml:\n\n```yml\nschema: http://localhost:4000\ndocuments: ./src/graphql/*.graphql\noverwrite: true\ngenerates:\n  ./src/graphql/index.ts:\n    - apollo-hooks-codegen\n      # Options here:\n      idType: any  # The Typescript type generated for GraphQL's \"ID\" type (defaults to string)\n      scalarTypes: # The Typescript types generated for custom scalar types in the GraphQL schema (defaults to any)\n        JSON: string\n        UTCDate: unknown\n\n```\n\n## Future Work\n\n- Suspense support\n- Default values\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpothos-dev%2Fapollo-hooks-codegen","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpothos-dev%2Fapollo-hooks-codegen","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpothos-dev%2Fapollo-hooks-codegen/lists"}