Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/app/(protected)/goals/[goalId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ export default async function GoalsPage({ params }: GoalsPageProps) {
auth: "access",
}),
}),
queryClient.prefetchQuery({
queryKey: goalsQueryKeys.detail(Number(goalId)),
queryFn: () =>
backendFetch<GoalResponse>(`/goals/${goalId}`, {
auth: "access",
}),
}),
]);

return (
Expand Down
74 changes: 72 additions & 2 deletions src/hooks/queries/goals/useDeleteGoalMutation.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,84 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
useMutation,
useQueryClient,
InfiniteData,
} from "@tanstack/react-query";
import { deleteGoal } from "@/api/goal";
import goalsQueryKeys from "./queryKeys";
import { useRouter } from "next/navigation";
import { Goal, GoalResponse } from "@/api/types/goal";

type GoalsCache =
| { nextCursor: number | null; totalCount: number; goals: Goal[] }
| undefined;

export function useDeleteGoalMutation() {
const queryClient = useQueryClient();
const router = useRouter();

return useMutation({
mutationFn: (goalId: number) => deleteGoal(goalId),

onMutate: async (goalId) => {
await queryClient.cancelQueries({
queryKey: goalsQueryKeys.detail(goalId),
});
await queryClient.cancelQueries({
queryKey: goalsQueryKeys.list(),
});
await queryClient.cancelQueries({
queryKey: goalsQueryKeys.infinite(),
});

queryClient.setQueriesData<GoalsCache>(
{ queryKey: goalsQueryKeys.list() },
(old) => {
if (!old?.goals) return old;
return {
...old,
totalCount: old.totalCount - 1,
goals: old.goals.filter((goal) => goal.id !== goalId),
};
},
);

queryClient.setQueriesData<InfiniteData<GoalResponse>>(
{ queryKey: goalsQueryKeys.infinite() },
(old) => {
if (!old?.pages) return old;
return {
...old,
pages: old.pages.map((page) => ({
...page,
totalCount: page.totalCount - 1,
goals: page.goals.filter((goal) => goal.id !== goalId),
})),
};
},
);

queryClient.removeQueries({
queryKey: goalsQueryKeys.detail(goalId),
});
},

onSuccess: () => {
queryClient.invalidateQueries({
queryKey: goalsQueryKeys.all,
queryKey: goalsQueryKeys.list(),
});
queryClient.invalidateQueries({
queryKey: goalsQueryKeys.infinite(),
});

router.replace("/dashboard");
},

onError: () => {
queryClient.invalidateQueries({
queryKey: goalsQueryKeys.list(),
});
queryClient.invalidateQueries({
queryKey: goalsQueryKeys.infinite(),
});
},
});
Expand Down