Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `writeQuery` and `writeData` in Apollo client?

According to the docs on local state management, one can use both writeData and writeQuery for appending data to the cache.

What are the best practices here? When to one over the other?

like image 745
Paul Razvan Berg Avatar asked Dec 17 '22 15:12

Paul Razvan Berg


1 Answers

From the documentation:

To write the data to the cache, you can use either cache.writeQuery or cache.writeData. The only difference between the two is that cache.writeQuery requires that you pass in a query to validate that the shape of the data you're writing to the cache is the same as the shape of the data required by the query. Under the hood, cache.writeData automatically constructs a query from the data object you pass in and calls cache.writeQuery.

The only difference is: do you construct the query that is passed (by calling cache.writeQuery directly), or do you let Apollo handle it (by calling cache.writeData)?

From looking at the source of cache.writeData on GitHub, it seems that Apollo will perform some analysis on the data you give it to determine the best way to use it, while cache.writeQuery will straight up take the query you pass it and use that.

So, to summarise:

cache.writeQuery

  • Pros: probably faster, provides data shape validation
  • Cons: you have to provide a query yourself

cache.writeData

  • Pros: you let Apollo handle building the query
  • Cons: might be slower, no data shape validation
like image 78
gueorgui Avatar answered Dec 20 '22 03:12

gueorgui