All files / src/hooks/cache useUpdateTaskCache.ts

94.73% Statements 18/19
71.42% Branches 5/7
100% Functions 6/6
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61                  346x 2454x     346x     346x 247x 99x   41x 41x         12245x 12245x   12245x   374x 234x         208x         234x       140x               138x            
import { useAppDispatch } from "@/store/hooks.ts";
import { api, PaginatedTaskListRead, TaskRead } from "@/api/apiStore.gen.ts";
import { useProjectId } from "@/hooks/project.ts";
 
function updateTaskInList(
  task: TaskRead,
  paginatedTasks: PaginatedTaskListRead,
  updateOnly: boolean,
) {
  const tasks = paginatedTasks?.results || ([] as TaskRead[]);
  const taskIndex = tasks.findIndex((t) => t.id === task.id);
 
  // If results is null, initialize it with the current tasks
  Iif (paginatedTasks.results == null) paginatedTasks.results = tasks;
 
  // Update the task in the list if it exists
  if (taskIndex !== -1) {
    tasks[taskIndex] = task;
  } else if (!updateOnly) {
    // If the task does not exist, add it to the list
    tasks.unshift(task);
    paginatedTasks.count += 1;
  }
}
 
export function useUpdateTaskCache() {
  const dispatch = useAppDispatch();
  const flowsheetId = useProjectId();
 
  return (updatedTask: TaskRead) => {
    // Update the standard task list cache if this task is not a child task
    if (updatedTask.parent === null) {
      dispatch(
        api.util.updateQueryData(
          "coreTasksList",
          { page: 1, flowsheet: flowsheetId },
          (paginatedTasks) => {
            updateTaskInList(updatedTask, paginatedTasks, false);
          },
        ),
      );
 
      return;
    }
 
    // Update the child task list cache
    dispatch(
      api.util.updateQueryData(
        "coreTasksChildrenList",
        {
          id: updatedTask.parent as number,
          page: 1,
        },
        (paginatedTasks) => {
          updateTaskInList(updatedTask, paginatedTasks, true);
        },
      ),
    );
  };
}