1
1
import { gql , useMutation } from '@apollo/client'
2
- import { ALL_POSTS_QUERY , allPostsQueryVars } from './PostList'
3
2
4
3
const CREATE_POST_MUTATION = gql `
5
4
mutation createPost($title: String!, $url: String!) {
@@ -26,19 +25,22 @@ export default function Submit() {
26
25
27
26
createPost ( {
28
27
variables : { title, url } ,
29
- update : ( proxy , { data : { createPost } } ) => {
30
- const data = proxy . readQuery ( {
31
- query : ALL_POSTS_QUERY ,
32
- variables : allPostsQueryVars ,
33
- } )
34
- // Update the cache with the new post at the top of the list
35
- proxy . writeQuery ( {
36
- query : ALL_POSTS_QUERY ,
37
- data : {
38
- ...data ,
39
- allPosts : [ createPost , ...data . allPosts ] ,
28
+ update : ( cache , { data : { createPost } } ) => {
29
+ cache . modify ( {
30
+ fields : {
31
+ allPosts ( existingPosts = [ ] ) {
32
+ const newPostRef = cache . writeFragment ( {
33
+ data : createPost ,
34
+ fragment : gql `
35
+ fragment NewPost on allPosts {
36
+ id
37
+ type
38
+ }
39
+ ` ,
40
+ } )
41
+ return [ newPostRef , ...existingPosts ]
42
+ } ,
40
43
} ,
41
- variables : allPostsQueryVars ,
42
44
} )
43
45
} ,
44
46
} )
0 commit comments