Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Apollo client optimistic update changes reference for every list item?

  1. I have parent component A from where I am fetching TODO list (lets say 10 item), then mapping this array and passing whole object to component B.

  2. Component B has a memo wrapper to compare todo object references to re-render only updated component. Sth like:

    export default memo(ComponentB, (prevProps, nextProps) => {  
     return prevProps.TODO === nextProps.TODO
    })
    
  3. From component B on button click call useMutation to add one item inside list. I provided optimisticResponse and update function as it was on Apollo doc

  4. Everything is working fine except: When I am adding optimisticResponse for fast UI change and log inside component B, I see that every list item is re-rendering, BUT in case I just leave update function without optimisticResponse then I see that only one item re-rendered.

So my question is, is this how Apollo treats optimisticResponse update or I should continue looking for some issue in my code and I am trying to figure out hours already :/

I just couldn't found any material yet which points out this particular case and if someone knows answer, maybe share the link or small suggestion. Thank you!

like image 435
Vano Avatar asked Nov 06 '22 04:11

Vano


1 Answers

The optimistic response is committed to the cache, so you're logic will "think" that the data has updated. After the server responds, the cache is reverted and the real data is applied. So, in fact, you will experience 2 updates when you might have expected only 1.

Besides that, I believe you're saying that you have a component rendered for every "TODO" item. AKA, you're not passing an array to a single component. That sounds like the right method, just making sure that's what you have. So why do they all update? It doesn't seem like you need to worry about the apollo code for this issue. I think the first step is to change the line,

return prevProps.TODO === nextProps.TODO

to be a comparison that DOES NOT depend on references. Instead, the simplest quick change would be if there's some string ID field on the TODO. In that case you could do,

return prevProps.TODO.id === nextProps.TODO.id

This way you don't have to worry about whether apollo is returning the same reference or a new object with the same data. If that doesn't fix it, let me know in the comments and we can keep looking.

like image 69
Nicholas Harder Avatar answered Nov 15 '22 07:11

Nicholas Harder