optimisticResponse vs update in Apollo Client?
They do different things. optimisticResponse
predicts the response from the server. If you are updating a node already in the store then this is probably all you need.
The update
function gives you full control over your store. If for instance you have created a new node then you will need to add it to the relevant query. As it's a new entity Apollo doesn't automatically know what to do with it.
Optimistic response used to modify store without response from backend. Store updates itself when receives fresh data
Update used to modify store using response from backend. Store doesn’t update itself
To expand on the other two answers, the distinction lies in whether or not the thing you are 'updating' already exists in the cache or not.
As per the docs, if you are updating an existing item, say editing a title of a todo item, you only need optimisticResponse
. Why? because the cache contains the node, and you only need to tell it that something new happened with the new node, which is immediately reflected on the UI.
optimisticResponse
just provides an 'immediate' result data from a mutation.
Now we have a second case, you want to add a new Todo item to the list. First, the cache needs to know that a new item is created. As soon as you provide the update
attribute to a Mutation, you are taking control of the caches' state.
update
takes place ofrefetchQueries
, which means you are in control of the cache state.
With update
you can reach into the cache and modify/append exclusively the node you need, as opposed to maybe refetching an entire hierarchy of data. However, you are still waiting for the Mutation to finish. If you provide the update
along side the optimisticResponse
, you are providing an immediate assumed response, and giving it to your personal update
function, which then instantly updates the cache.
The reason these two are paired in scenario two, is that you are completely bypassing the server responses. If you just give a 'immediate' response, Apollo is still in the mode where it waits for the server to update cache. update
lets you highjack that as well, and do it client side.
Final Note: you are assuming the server is always responding without errors. Error handling elsewhere will still work, but you might get into UI inconsistencies if you are frequently catching errors (say
isLoggedIn
scenarios) so def make sure that the queries you 'fast track' are typically healthy.