Relay Modern - Optimistic Updates
Relay Modern provides an update way that solves the delay to update client data after a server request.
It consists in updating 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 returns an error, the client data will get a rollback.
What happens if server response was different from updated data?
If server response is different from the updated data, Relay will apply server data ensuring consistency.
Without Optimistic Update
With Optimistic Update
optimisticResponse is an object that reflects 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.
Code and instructions can be found here.
Any issues or questions, send me a message. You can find me at GitHub and Twitter.