-
Notifications
You must be signed in to change notification settings - Fork 22
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Optimistic Response with debounce mutations #14
Comments
I managed to solve this same problem by using custom debouncing, without using In a nutshell, for the mutations that I want to debounce, I call a wrapper function which:
|
@PeterDekkers could you share your implementation? |
@edgars-sirokovs, something like this: import React from 'react';
import debounce from 'lodash/debounce';
import { useApolloClient, useMutation } from '@apollo/client';
const UPDATE_DEBOUNCE_TIME = 1500;
const mutationQuery = gql`
mutation Blah($input: Input!) {
updateQuery(input: $input) {
yourQueryHere
}
}
`;
function useDebouncedMutation() {
const [doUpdate] = useMutation(mutationQuery);
const client = useApolloClient();
const debouncedUpdate = React.useMemo(
() =>
debounce(doUpdate, UPDATE_DEBOUNCE_TIME, {
// Send one immediately
leading: true,
}),
[doUpdate],
);
return async ({
mutationInput
}) => {
// Replace this with your way to retrieve the optimistic result
const optimisticResult = getOptimisticResult(mutationInput);
const queryVariables = {
input: mutationInput
};
const queryData = {
doUpdate: {
__typename: 'UpdateMutation',
foo: bar,
},
};
// Write to cache for instant UI update.
// An alternative to `optimisticResponse`, as the mutations are debounced.
client.writeQuery({
query: mutationQuery,
variables: queryVariables,
data: queryData,
overwrite: true,
});
return debouncedCartUpdate({
variables: queryVariables,
ignoreResults: true,
// Don't write to cache again, we've done that already above.
// Furthermore, writing to cache here causes a performance
// issue, where `writeQuery` doesn't immediately update cache
// when requests are in flight, making the UI seem sluggish.
// This does mean that the optimistic cart response is taken
// for truth.
fetchPolicy: 'no-cache',
});
};
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
code example:
This is optimistic query
This is Mutation:
And this is my init
The text was updated successfully, but these errors were encountered: