Apollo client: Optimistic update for adding a list item where item detail query is separate causes cache miss

Viewed 63

I have a list of items whose ids are queried initially and then for each I render its own component instance that does another query for the details.

When you add an item, the optimistic update (and subsequent mutation response) store that item in your cache but of course it is not added to the list. So I write to the cache for the list query manually in the mutation's update callback.

This makes a new instance of the item component be rendered for that id, and the query for the details in that component should find the item in the cache and render the item with our optimistic details. However, this is not the case.

When a new instance of the item component is rendered for our optimistic id and the query for the details should find the item in the cache, it doesn’t even though it is there. What you see is a blank item added to the list (the component returns null if no data) before the mutation finally succeeds. When it succeeds, then the item is rendered with its details.

I have a minimum reproducible example here. You will notice that I make the item render "not found" when it's not found and that is what is rendered until the mutation request succeeds (ie, the optimistic response is not working).

1 Answers

In my opinion the behavior is correct like that.
Imagine that the user relies on the cache and uses the objects in the cache and then the objects never get persisted, either because they are deleted again before they are even saved or because some error occurs. Then all the connections based on these cache-objects are broken and perhaps impossible to repair.

Related