TanStackT
TanStack2y ago
2 replies
systematic-tan

Mutation optimistic updated slows down the UI

I have an app in which a user can upload files and then interact with them - add to favorite, change display name, etc..
One of the functionalities is to delete a file.
I use tanstack mutation to do optimistic updates for the files deletion - all the files are inside a table.

const mutation = useMutation({
    mutationFn: fileService.deleteFile,
    mutationKey: ["delete", id],
    onSettled: async () => {
      queryClient.invalidateQueries({
        queryKey: filesKeys.getFilesKey(),
      });
    },
    onMutate: async () => {
      const previousFiles = queryClient.getQueryData<File[]>(filesKeys.getFilesKey());

      const newFiles = previousFiles?.filter((file) => file.fileId.toString() !== id);
      queryClient.setQueryData(filesKeys.getFilesKey(), newFiles ?? []);

      return { previousFiles };
    },
    onError: (_error, _variables, context) => {
      if (context) {
        queryClient.setQueryData(filesKeys.getFilesKey(), context.previousFiles);
      }

      message.error({
        content: "Error deleting file",
        key: "delete-file",
      });
    },
  });


There is nothing special in this specific example.
When a user click the button the onMutate function fires and it filters the files to remove the file id.
The problem it that is slows down the UI, not by a lot of course but in some sense.
I've added a video for reference - in this video I have around 200 files that it filter.
I'd appreciate any answer and if it is a problem at all.
Was this page helpful?