Reputation: 764
I'm using an Apollo local in-memory cache for my app's state management. In my cache I have an array called Clips
. Somewhere in my app I need to go through the list of clips and mutate data on them. I can do it like this:
const client = useApolloClient();
client.writeData({ data: { clips: mutatedClipsArray }});
But is there a way that I could write data for only a specific index of the clips array? Something like this (which doesn't work):
client.writeData({ data: { clips[2]: mutatedClip2 }});
Upvotes: 2
Views: 2144
Reputation: 9671
React relies on shallow compare to diff and re-render the UI.
mutating an array element doesn't change the memory address of the array variable, so react wouldn't know that array has changed because an element of array has changed, checking each element has changed can become expensive, so you have to give a new array with the new element in the array to make react re-renders.
For apollo cannot do it directly, but you can read the cache and merge them back
const currentClips = readQuery({ query: QUERY, variables })
currentClips.data.clips[2] = newClip;
client.writeData({ data: { clips: currentClips.data.clips }});
But React would not likely to re-render correctly, so this might be better:
const currentClips = readQuery({ query: QUERY, variables })
const newClips = [...currentClips.data.clips]; make a copy
newClips[2] = newClip;
client.writeData({ data: { clips: newClips }});
** Above just sample code, you might have to verify the shape of currentClips
Upvotes: 3