Skip to content

Commit

Permalink
After createOneDbConnection mutation, update cache manually instead o…
Browse files Browse the repository at this point in the history
…f using refetchQuery (#5684)

Closes #5057.

RefetchQuery is unreliable - [it won't be executed if the component is
unmounted](apollographql/apollo-client#5419),
which is the case here because of the redirection that occurs after the
mutation.
We want to avoid using refetchQuery as much as possible, and write
directly in the cache instead.
  • Loading branch information
ijreilly authored May 31, 2024
1 parent c7f2150 commit 5e1dfde
Showing 1 changed file with 23 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { ApolloClient, useMutation } from '@apollo/client';
import { getOperationName } from '@apollo/client/utilities';

import { CREATE_ONE_DATABASE_CONNECTION } from '@/databases/graphql/mutations/createOneDatabaseConnection';
import { GET_MANY_DATABASE_CONNECTIONS } from '@/databases/graphql/queries/findManyDatabaseConnections';
Expand All @@ -9,6 +8,7 @@ import {
CreateServerMutation,
CreateServerMutationVariables,
} from '~/generated-metadata/graphql';
import { isDefined } from '~/utils/isDefined';

export const useCreateOneDatabaseConnection = () => {
const apolloMetadataClient = useApolloMetadataClient();
Expand All @@ -27,8 +27,28 @@ export const useCreateOneDatabaseConnection = () => {
variables: {
input,
},
awaitRefetchQueries: true,
refetchQueries: [getOperationName(GET_MANY_DATABASE_CONNECTIONS) ?? ''],
update: (cache, { data }) => {
const createdRemoteServer = data?.createOneRemoteServer;
if (!createdRemoteServer) return;

const getManyDatabaseConnectionsQuery = {
query: GET_MANY_DATABASE_CONNECTIONS,
variables: {
input: { foreignDataWrapperType: input.foreignDataWrapperType },
},
};

if (isDefined(cache.readQuery(getManyDatabaseConnectionsQuery))) {
cache.updateQuery(getManyDatabaseConnectionsQuery, (cachedQuery) => ({
findManyRemoteServersByType: [
...cachedQuery.findManyRemoteServersByType,
createdRemoteServer,
],
}));

return;
}
},
});
};

Expand Down

0 comments on commit 5e1dfde

Please sign in to comment.