Open jaril5976 opened 3 years ago
I managed to solve this same problem by using custom debouncing, without using apollo-link-debounce
.
In a nutshell, for the mutations that I want to debounce, I call a wrapper function which:
optimisticResponse
and updates the UI instantly.optimisticResponse
, as the data is already written to the cache).@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',
});
};
}
code example:
This is optimistic query
This is Mutation:
And this is my init