VulcanJS / Vulcan

🌋 A toolkit to quickly build apps with React, GraphQL & Meteor
http://vulcanjs.org
MIT License
7.98k stars 1.89k forks source link

Updating nested objects in the GraphQL cache #2516

Open SachaG opened 4 years ago

SachaG commented 4 years ago

Here's a pretty common scenario. I have a post object with comments subfield. The code could look something like this:

post.comments ? <PostComments comments={post.comments}/> : <p>Leave the first comment!</p>

Notice that I'm not loading comments through their own useMulti/withMulti hook/HoC but as part of the query that loads the post.

Because of that, when I add a comment the post.comments nested field will not update until I either reload the page or the poll interval kicks in and the whole post is loaded again.

As discussed with @doronrk, the way around this would be to set up some kind of system that recursively traverses the GraphQL tree and calls each resolver (in this case post.comments) again to update it on the client based on the new comment in cache.

This could be pretty complex, and also would not necessarily work for resolvers that are server-only (such as anything that directly makes a database or API call). But maybe we could at least implement it for the standard hasOne, hasMany, etc. relations, since those represent most of such use cases?

eric-burel commented 4 years ago

Not sure where I listed the relevant issues in Apollo, maybe here: https://github.com/VulcanJS/Vulcan/issues/2381

Basically the cache update system is architectured so that mutations are responsible to update queries. But that's weird, because a comment creation shouldn't be responsible to updating posts for example (they may not even know the posts they are related to). Someone proposed to reverse this thinking, and have queries to subscribe mutations. So here, your post query could subscribe to both comment creation and post creation for example. Sadly that's not the case so a solution to this might be complex/hackish.