Skip to content

Commit

Permalink
safely dispose of client instance
Browse files Browse the repository at this point in the history
  • Loading branch information
justinadkins committed Oct 15, 2024
1 parent 15e3584 commit 605fcc3
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion packages/web/src/apollo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ export type GraphQLClientConfigProp = Omit<
link?: ApolloLink | RedwoodApolloLinkFactory
}

/** Local variable to keep track of current ApolloClient instance. */
let _client: ApolloClient<unknown> | undefined

const ApolloProviderWithFetchConfig: React.FunctionComponent<{
config: Omit<GraphQLClientConfigProp, 'cacheConfig' | 'cache'> & {
cache: ApolloCache<unknown>
Expand Down Expand Up @@ -299,7 +302,12 @@ const ApolloProviderWithFetchConfig: React.FunctionComponent<{
}

const client = React.useMemo(() => {
return new ApolloClient({
// If we have a client instance, stop it before creating a new one.
if (_client) {
_client.stop()
}

_client = new ApolloClient({
// Default options for every Cell. Better to specify them here than in `beforeQuery` where it's too easy to overwrite them.
// See https://www.apollographql.com/docs/react/api/core/ApolloClient/#example-defaultoptions-object.
defaultOptions: {
Expand All @@ -319,6 +327,8 @@ const ApolloProviderWithFetchConfig: React.FunctionComponent<{
link,
...otherClientConfig,
})

return _client
// eslint-disable-next-line react-hooks/exhaustive-deps -- `link` is not stable, we use `useEffect` below to update it.
}, [otherClientConfig])

Expand Down

0 comments on commit 605fcc3

Please sign in to comment.