Updating an object with a mutation that returns a different type #1147

SachaG opened this Issue Jan 9, 2017 · 4 comments


None yet

4 participants

SachaG commented Jan 9, 2017

I have a vote mutation that’s used to upvote different types of documents: posts, comments, etc. Since I want to use a single mutation for all these types I can’t have it return a Post or Comment type, so I created a new VoteResult type. And I’m using dataIdFromObject, so the update happens automatically as soon as the mutation returns.

The optimistic response works properly (I’m setting the __typename manually), but when the mutation returns the real result, something goes wrong and the optimistic response is overturned

Could this be because the mutation doesn't return an object of the same GraphQL type as the object in the store that needs to be updated? In other words, can a mutation that returns type A be used to update a document of type B in the store?

By the way I can confirm that if both types are the same (i.e. I change vote to return Post object), I’m not seeing any issues.

stubailo commented Jan 9, 2017

something goes wrong and the optimistic response is overturned

The optimistic update is always removed once the response from the server is received. You have a few options:

  1. Modify your mutation to return an object of the correct type by using an interface. Define an interface called Votable with a field votes, and have all types that can be upvoted belong to that. Since __typename will be correct, everything will work as planned.
  2. Use reducers or updateQueries to update the objects manually.
  3. Write a custom reducer on the store to update the appropriate object (right now we don't have a specific feature for updating an object manually but we should)

I think (1) is the best option because it makes sense to me that an API that updates an object would return that type of object.

SachaG commented Jan 9, 2017

Oh you're right, an interface sounds exactly like what I need, thanks! I'll read up on that and report back :)

rnenjoy commented Jan 9, 2017 edited

@SachaG some code example when you have a working version of this would be great to see! We should even put it in the documentation since i think many people will run into this.


Agree with @rnenjoy. Please let us know the solution. Very interesting.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment