Member-only story

A Small Helper Function for Conditional Requests in Apollo GraphQL

Perttu Lähteenlahti
2 min readFeb 23, 2024

--

In a project I’m working on, we have a case where many of the queries ran using the autogenerated Apollo GrapQL hooks that depend on the userID. However, this ID might be null at times, such as when the user's authentication session has ended. This leads to issues in two places:

  • The hook will try to run with a query that has no userID, leading the backend to reject it and return no data/error message on null format userID
  • Typescript will complain about userID possibly being undefined or null

The first one is easy to fix using Apollo GraphQL hooks skip option. However as that does not validate the type, this leads to TypeScript complaining that you're trying to pass a null value to a field that does not accept one (as was in our case). To get around this our team had decided to use non-null assertation with the exclamation mark:

Now this works all the way until someone asserts a variable as non-null but forgets to add it to the skip section, leading to runtime errors or unexpected behavior. Also, since our project is relatively mature and enforces several linting rules to capture these kinds of things, people had started adding a lot eslint-disable-next-line @typescript-eslint/no-non-null-assertion comments into these hooks. I think that you should try to always figure out a way around disabling a rule if you're disabling it more than once in your codebase.

--

--

Perttu Lähteenlahti
Perttu Lähteenlahti

No responses yet