Skip to content

Commit a79bcfb

Browse files
authored
Fix with-apollo example (#17686)
# Issue The cache updates are performed in a wrong way, resulting in a duplicate collection: **Error:** ```log webpack-internal:///./node_modules/react-dom/cjs/react-dom.development.js:88 Warning: Encountered two children with the same key, `6f3f7265-0d97-4708-a3ea-7dee76dc0a0a`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version. ``` **Video:** ![broken](https://user-images.githubusercontent.com/1265681/95336501-0c170180-08b1-11eb-9273-6ac9e37ceb41.gif) # Fix **Video:** ![fixed](https://user-images.githubusercontent.com/1265681/95336538-15a06980-08b1-11eb-8d5e-6acc07e16138.gif)
1 parent b2d1d87 commit a79bcfb

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

examples/with-apollo/components/Submit.js

+15-13
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { gql, useMutation } from '@apollo/client'
2-
import { ALL_POSTS_QUERY, allPostsQueryVars } from './PostList'
32

43
const CREATE_POST_MUTATION = gql`
54
mutation createPost($title: String!, $url: String!) {
@@ -26,19 +25,22 @@ export default function Submit() {
2625

2726
createPost({
2827
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+
},
4043
},
41-
variables: allPostsQueryVars,
4244
})
4345
},
4446
})

0 commit comments

Comments
 (0)