2

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 }});

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

instead of client.writeData, use the client.writeQuery ---> this will ensure the rerendering happening correctly.
this is a useless action with a spread operator, Apollo does this on its own

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.