Skip to content

Instantly share code, notes, and snippets.

@andycarrell
Created November 3, 2020 18:46
Show Gist options
  • Save andycarrell/c7f99016a25dc7e48605a969e8b9fa38 to your computer and use it in GitHub Desktop.
Save andycarrell/c7f99016a25dc7e48605a969e8b9fa38 to your computer and use it in GitHub Desktop.
import { useCallback } from "react";
import { useApolloClient } from "@apollo/client";
import { defaultDataIdFromObject } from "@apollo/client/core";
const useApolloCacheEvict = () => {
const { cache } = useApolloClient();
/**
* Pass entire objects as queried from the cache.
* Use Apollo's default function to determine id.
*/
const evictObjectsFromCache = useCallback(
(...objects) => {
objects.map(defaultDataIdFromObject).forEach((id) => {
cache.evict({ id });
});
/**
* Evicting an object often makes other cached objects unreachable.
* Call cache.gc after evicting object(s) from the cache.
*/
cache.gc();
},
[cache],
);
return evictObjectsFromCache;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment