Using Apollo React Hooks with Typescript - Dgraph Blog

I started to use this graphql-codegen a bit now. Here is what I have found.

The graphql-codegen can be tied in with Apollo Client and with the proper configuration, it will generate custom hooks for queries and mutations using your operation files.

Being that is uses Apollo Client for these custom hooks under the hood, it all works seamlessly. The important facts to remember:

  1. Any data that you mutate and want to updated in the cache, be sure to return it in the payload of the mutation.
  2. By default Apollo Client is configured to only use id or _id to uniquely identify the cache to update. So if you want to the payload to update the cache, include the ids’s as well.
  3. (2B reallly) If your type uses a field for ID or @id other than default above, then you must configure your cache to use these custom identifiers.
  4. Apollo Client does not know the difference between update and delete operations. I wrote a function to Use the Payload to Delete from Apollo Cache that you can pass to the update prop which will delete any items by unique identifier from the payload when attached. Unfortunately, there is no way that I have found to include this script in the codegen hooks, so you have to manually include it any time you call a useDelete* hook.

This exact use case is not automatic because in essence the generated hooks are all separate entities other than sharing some types. So in the generated code, the useAddToDo hook would not know to update the cache of the useQueryToDo hook. And even if it did, that may not always be what was wanted. You can pass variables into the hooks in different places so you may only want one use of the hook to be updated and not every other use.

1 Like