Created
February 8, 2021 17:49
-
-
Save tvler/0a158e651dc88ec43094584b72789b70 to your computer and use it in GitHub Desktop.
WriteFragment: A declarative way to write fragments to Apollo cache using React components
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 { useApolloClient, Cache } from "@apollo/client"; | |
import { useEffect } from "react"; | |
/* | |
* WriteFragment: A declarative way to write fragments to Apollo cache | |
* using React components. When the fragment props change, the cache is | |
* updated. When then component unmounts, the fragment is deleted. | |
* | |
* This is essentially a reactive version of the cache.writeFragment | |
* method, using the same exact arguments and types. | |
* | |
* writeFragment API: apollographql.com/docs/react/api/cache/InMemoryCache/#writefragment | |
* | |
* Ex: | |
* const fragment = gql`fragment UserFragment on User { id name }`; | |
* const data = { | |
* __typename: "User", | |
* id: 123, | |
* name: "Tyler Deitz", | |
* }; | |
* | |
* // Then, somewhere in your JSX | |
* | |
* <WriteFragment fragment={fragment} data={data} /> | |
*/ | |
export const WriteFragment: React.FC<Cache.WriteFragmentOptions<any, any>> = ({ | |
fragment, | |
data, | |
broadcast, | |
id, | |
fragmentName, | |
variables, | |
}) => { | |
const { cache } = useApolloClient(); | |
useEffect(() => { | |
cache.writeFragment({ | |
fragment, | |
data, | |
broadcast, | |
id, | |
fragmentName, | |
variables, | |
}); | |
return () => { | |
const normalizedIdentity = cache.identify(data); | |
if (normalizedIdentity !== undefined) { | |
cache.evict({ id: normalizedIdentity }); | |
cache.gc(); | |
} | |
}; | |
}, [broadcast, cache, data, fragment, fragmentName, id, variables]); | |
return null; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment