Optimistic Updates with Apollo Client
Unanswered
Mini Satin posted this in #help-forum
Mini SatinOP
does cache.evict() or cache.gc() initiate re-render in react? I am trying to do optimistic update and in update handler of my mutation I am calling evict and gc, but it doesnt re-render my components instantly
handler:
Does
Does it triggers a refresh like:
import type { MutationFunctionOptions } from "@apollo/client";
import { useMutation } from "@apollo/client";
import { DELETE_ITEMS } from "../queries";
import type { DeleteItemsMutation, DeleteItemsMutationVariables } from "../types/api";
type MutationOptions = MutationFunctionOptions<DeleteItemsMutation, DeleteItemsMutationVariables>;
type Options = { mutation?: MutationOptions };
type UseMutation = typeof useMutation<DeleteItemsMutation, DeleteItemsMutationVariables>;
const useDeleteItems = (options?: Options): ReturnType<UseMutation> => {
return useMutation<DeleteItemsMutation, DeleteItemsMutationVariables>(DELETE_ITEMS, {
update(cache, { data }) {
if (!data) {
return;
}
for (const id of data.deleteItems) {
cache.evict({ id: `Item:${id}` });
}
cache.gc();
},
...options?.mutation,
});
};
export default useDeleteItems;handler:
const handleDeleteClicked = (): void => {
deleteItems({
variables: { ids: [item.id] },
onCompleted: () => {
toast.success(<DeleteItemsToast item={item} />);
},
optimisticResponse: { deleteItems: [item.id] },
});
};Does
evict method has the same effect as this:Like writeQuery and writeFragment, modify triggers a refresh of all active queries that depend on modified fields (unless you override this behavior by passing broadcast: false).Does it triggers a refresh like:
writeQuery writeFragment and modify ?2 Replies
Red-tailed wasp
I haven’t had success with using evict with useQuery/useSuspenseQuery. In those cases I’m not sure how it would know to re-run the query based on that row being in the result.
What has worked for me is:
- Perform a query
- Pass ids to a subcontinent
- In that component, use useFragment to look up the item and display it
That way, in the single component view you can program for what happens on delete.
However if a new item is added, i needed to specify refreshQueries in the create mutation.
Following this thread to see if others have better solutions. 😅
What has worked for me is:
- Perform a query
- Pass ids to a subcontinent
- In that component, use useFragment to look up the item and display it
That way, in the single component view you can program for what happens on delete.
However if a new item is added, i needed to specify refreshQueries in the create mutation.
Following this thread to see if others have better solutions. 😅
Mini SatinOP