Created
March 5, 2021 17:02
-
-
Save jschmidtnj/255b99f7449746e8be8f783e4c9a9fd0 to your computer and use it in GitHub Desktop.
graphql apollo cache setup
This file contains hidden or 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
| 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