From a79bcfb73ad79a9898ee30580fab45379e7840bf Mon Sep 17 00:00:00 2001 From: Henrik Wenz Date: Thu, 8 Oct 2020 05:45:28 +0200 Subject: [PATCH] Fix with-apollo example (#17686) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # 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) --- examples/with-apollo/components/Submit.js | 28 ++++++++++++----------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/examples/with-apollo/components/Submit.js b/examples/with-apollo/components/Submit.js index a276050ad51671f..8aa1d13265fc7e1 100644 --- a/examples/with-apollo/components/Submit.js +++ b/examples/with-apollo/components/Submit.js @@ -1,5 +1,4 @@ import { gql, useMutation } from '@apollo/client' -import { ALL_POSTS_QUERY, allPostsQueryVars } from './PostList' const CREATE_POST_MUTATION = gql` mutation createPost($title: String!, $url: String!) { @@ -26,19 +25,22 @@ export default function Submit() { createPost({ variables: { title, url }, - update: (proxy, { data: { createPost } }) => { - const data = proxy.readQuery({ - query: ALL_POSTS_QUERY, - variables: allPostsQueryVars, - }) - // Update the cache with the new post at the top of the list - proxy.writeQuery({ - query: ALL_POSTS_QUERY, - data: { - ...data, - allPosts: [createPost, ...data.allPosts], + update: (cache, { data: { createPost } }) => { + cache.modify({ + fields: { + allPosts(existingPosts = []) { + const newPostRef = cache.writeFragment({ + data: createPost, + fragment: gql` + fragment NewPost on allPosts { + id + type + } + `, + }) + return [newPostRef, ...existingPosts] + }, }, - variables: allPostsQueryVars, }) }, })