Skip to content

Instantly share code, notes, and snippets.

@pieterjandebruyne
Last active January 23, 2024 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pieterjandebruyne/ad195bfce757b340ee3ac105e74d40b5 to your computer and use it in GitHub Desktop.
Save pieterjandebruyne/ad195bfce757b340ee3ac105e74d40b5 to your computer and use it in GitHub Desktop.
useApolloCache
import { DocumentNode, useApolloClient } from '@apollo/client';
interface IApolloCacheReturn {
deleteApolloCacheForDocuments: (
documents: Array<DocumentNode>
) => Promise<void>;
}
export const useApolloCache = (): IApolloCacheReturn => {
const client = useApolloClient();
const getQueryNameFromDocument = (document: DocumentNode) => {
const definition = document.definitions[0];
if (definition && 'name' in definition) {
return definition.name?.value;
}
};
const deleteApolloCacheForDocuments = async (
documents: Array<DocumentNode>
) => {
const documentNames = documents.map((doc) => getQueryNameFromDocument(doc));
documentNames.forEach((docName) => {
if (docName) {
client.cache.evict({ fieldName: docName });
}
});
client.cache.gc();
};
return { deleteApolloCacheForDocuments };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment