Skip to content

Instantly share code, notes, and snippets.

@jschmidtnj
Created March 5, 2021 17:02
Show Gist options
  • Select an option

  • Save jschmidtnj/255b99f7449746e8be8f783e4c9a9fd0 to your computer and use it in GitHub Desktop.

Select an option

Save jschmidtnj/255b99f7449746e8be8f783e4c9a9fd0 to your computer and use it in GitHub Desktop.
graphql apollo cache setup
try {
const cacheData = cloneDeep(client.cache.readQuery<PostsQuery, PostsQueryVariables>({
query: Posts,
variables: args.postsVariables
}));
if (!cacheData) {
throw new Error('no cache data found');
}
const postCache = cacheData.posts.results.find(elem => elem.id === args.data.id);
const addReactionRes = await client.mutate<AddReactionMutation, AddReactionMutationVariables>({
mutation: AddReaction,
variables: {
parent: args.data.id,
parentType: ReactionParentType.Post,
reaction: emoji
}
});
if (addReactionRes.errors) {
throw new Error(addReactionRes.errors.join(', '));
}
postCache.userReactions.push({
id: addReactionRes.data.addReaction,
type: emoji
});
postCache.reactionCount++;
if (args.data.userReactions.length > 0) {
const reactionID = args.data.userReactions[0].id;
const deleteReactionRes = await client.mutate<DeleteReactionMutation, DeleteReactionMutationVariables>({
mutation: DeleteReaction,
variables: {
id: reactionID
}
});
if (deleteReactionRes.errors) {
throw new Error(deleteReactionRes.errors.join(', '));
}
postCache.userReactions = postCache.userReactions.filter(elem => elem.id !== reactionID);
postCache.reactionCount--;
}
client.cache.writeQuery<PostsQuery, PostsQueryVariables>({
query: Posts,
variables: args.postsVariables,
data: cacheData
});
await args.updateData(false);
} catch (err) {
toast(err.message, {
type: 'error',
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment