React, Apollo, and the mystery of the canceled requests
The React app I’m working on was firing multiple Graphql Requests when there should have only been one. With the earlier identical requests being canceled.
My hunch told me this was an issue with react rendering and prop updates. Being new to the apollo client library I didn't really know where to start, so I worked inside out.
First I looked at my use of the `useLazyQuery` hook, which hands more granular control over when the graphql request is made. Being a god-fearing developer I decided that here was where the problem lay and changed the hook to the other apollo client API `useQuery`.
I reloaded the page and…
I had actually made the problem worse, now I had 3 more requests. This at least suggested the original hook `useLazyQuery` was doing something.
After another detour looking at the `useApolloClient` hook and trying to query using `client.query`, I started to hone in on the origin of the problem which was further up the component tree.
We are using OAuth to authenticate, retrieving a token, and then passing that through to the Apollo client
What was happening was the container which checked to see if a user was authenticated and then initiated Apollo client, was rendered more than expected after a user had been authenticated (I hope to be able to expand this article with more info once I actually figure out what happened in the render update cycle). The effect of this was that Apollo Client was being initiated twice. Hence the first set of canceled requests.
The quick and dirty way I fixed this problem was to use memoize from lodash to cache the return object of the getApolloClient function.