Avadhut Prabhudesai
Avadhut Prabhudesai

Reputation: 1

React apollo mutation and optimistic updates

I am using a graphql HOC with mutation for a input type of checkbox. I have also added optimistic UI update option to it. Checking the box will fire a mutation with value=true and unchecking will fire a mutation with value=false.

But the problem is rapid clicking results in multiple mutation calls to the server and there is a latency in responses. Meanwhile optimisticResponse update does its job and toggles the checkbox. When server response arrives, update function is called again and it toggles checkbox resulting in glitch in UI.

Let me summarize the flow I could anticipate

Order of clicks:

Check => Uncheck => Check

Order of UI updates:

Check(optimistic response) => Uncheck(optimistic response) => Check(server response) => Check(Optimistic response) => Uncheck(server response) => Check(server response)

Is there any way to remove these glitches?

Upvotes: 0

Views: 619

Answers (1)

Cory McAboy
Cory McAboy

Reputation: 332

There may be better options, but here are 2 that I came up with:

1) Alter break value=true and value=false into separate functions. That way, both your optimistic response and true update function perform the same operation. They would both call value=true or value=false.

2) For your optimistic response, you can add in an additional parameter of optimistic=true. Then in your update function, you can check to see whether optimistic is true. If it is, go ahead and make the update. After this check, you could then check the response of the mutation. If the mutation return an error, set the value back. If it does not return an error, do nothing.

if(optimistic) {
  setValue(); // Sets it to optimistic result
  return;
}
if(response returns error) {
  setValue(); // Returns it back to original state
  return
}

In my opinion, the better option is to go with 1, but if that is not possible, you can use 2 as a hacked option.

Upvotes: 0

Related Questions