Last active
January 23, 2024 20:52
-
-
Save pieterjandebruyne/ad195bfce757b340ee3ac105e74d40b5 to your computer and use it in GitHub Desktop.
useApolloCache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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