DEV Community

Cover image for Relay Modern — Optimistic Update
Lucas Besen
Lucas Besen

Posted on

5 1

Relay Modern — Optimistic Update

Relay Modern provides an update way that solves the delay to update client data from server response.

It consists in update the client data with an anticipated value that reflects server response.

I'll describe in this post one way to update client data using optimisticResponse.

What happens if something goes wrong?

In case server side returns an error, the client data will get a rollback.

What happens if server response was different from updated data?

If the server response was different from updated data, Relay will apply server data ensuring consistency.

Without Optimistic

Alt Text

With Optimistic

Alt Text

optimisticResponse is an object that reflect your mutation output and needs to be passed to commitMutation.

import { commitMutation } from 'react-relay';

// mutation
// variables

const optimisticResponse = {
  mutationName: {
    output: {
      data: value, 
    },
  },
};

commitMutation(
  env,
  {
    mutation,
    optimisticResponse,
    variables,
  },
);

Let's see a complete example:

import { commitMutation, graphql } from 'react-relay';

const mutation = graphql`
  mutation ReadMessageMutation($input: ReadMessageMutationInput!) {
    ReadMessage(input: $input) {
      message {
    status
      }
    }
  }
`;

const optimisticResponse = {
  ReadMessage: {
    message: {
      status: 'READ',
    },
  },
};

commitMutation(
  env,
  {
    mutation,
    optimisticResponse,
    variables,
  },
);

In the code above, I'm updating the message status before it returns from server side.

I've made a repository to benchmark updating data with and without optimistic update.

Alt Text

The code and instructions can be found here.

I hope you enjoy it, thanks for your time.

Any troubles or doubts, send me a message. You can find me at Github and Twitter.

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay