Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

1.9 KB
Raw Blame
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { CreateLabelRequest } from "@/fetchers/label/create-label";
import createLabel from "@/fetchers/label/create-label";
import { addLabelToTaskInTasksCache } from "./sync-task-labels-cache";

function useCreateLabel() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: createLabel,
    onSuccess: (createdLabel, variables: CreateLabelRequest) => {
      queryClient.setQueryData(
        ["labels", variables.workspaceId],
        (existingLabels: Array<typeof createdLabel> | undefined) => {
          if (!existingLabels) return [createdLabel];

          const alreadyExists = existingLabels.some(
            (label) => label.id === createdLabel.id,
          );

          return alreadyExists
            ? existingLabels
            : [...existingLabels, createdLabel];
        },
      );

      if (createdLabel.taskId) {
        queryClient.setQueryData(
          ["labels", createdLabel.taskId],
          (existingLabels: Array<typeof createdLabel> | undefined) => {
            if (!existingLabels) return [createdLabel];

            const alreadyExists = existingLabels.some(
              (label) => label.id === createdLabel.id,
            );

            return alreadyExists
              ? existingLabels
              : [...existingLabels, createdLabel];
          },
        );

        addLabelToTaskInTasksCache(queryClient, createdLabel.taskId, {
          id: createdLabel.id,
          name: createdLabel.name,
          color: createdLabel.color,
        });
      }

      void queryClient.invalidateQueries({
        queryKey: ["labels", variables.workspaceId],
      });

      if (createdLabel.taskId) {
        void queryClient.invalidateQueries({
          queryKey: ["labels", createdLabel.taskId],
        });
      }
    },
  });
}

export default useCreateLabel;