perf: improve optimistic queries

This commit is contained in:
Henry
2025-02-07 17:35:06 +00:00
parent fe45c31795
commit 328a3064bb
13 changed files with 200 additions and 195 deletions

View File

@@ -4,14 +4,19 @@ import { Fragment } from "react";
export default function Dropdown({ export default function Dropdown({
items, items,
children, children,
disabled,
}: { }: {
items: { label: string; action: () => void; icon?: React.ReactNode }[]; items: { label: string; action: () => void; icon?: React.ReactNode }[];
children: React.ReactNode; children: React.ReactNode;
disabled?: boolean;
}) { }) {
return ( return (
<Menu as="div" className="relative inline-block text-left"> <Menu as="div" className="relative inline-block text-left">
<div> <div>
<Menu.Button className="flex h-7 w-7 items-center justify-center rounded-[5px] hover:bg-light-200 dark:hover:bg-dark-200"> <Menu.Button
disabled={disabled}
className="flex h-7 w-7 items-center justify-center rounded-[5px] hover:bg-light-200 dark:hover:bg-dark-200"
>
{children} {children}
</Menu.Button> </Menu.Button>
</div> </div>

View File

@@ -1,13 +1,11 @@
import "~/styles/globals.css"; import "~/styles/globals.css";
import { type AppType } from "next/app"; import type { AppType } from "next/app";
import { Plus_Jakarta_Sans } from "next/font/google"; import { Plus_Jakarta_Sans } from "next/font/google";
import { ModalProvider } from "~/providers/modal"; import { ModalProvider } from "~/providers/modal";
import { BoardProvider } from "~/providers/board";
import { PopupProvider } from "~/providers/popup"; import { PopupProvider } from "~/providers/popup";
import { ThemeProvider } from "~/providers/theme"; import { ThemeProvider } from "~/providers/theme";
import { api } from "~/utils/api"; import { api } from "~/utils/api";
const jakarta = Plus_Jakarta_Sans({ const jakarta = Plus_Jakarta_Sans({
@@ -36,9 +34,7 @@ const MyApp: AppType = ({ Component, pageProps }) => {
<ThemeProvider> <ThemeProvider>
<ModalProvider> <ModalProvider>
<PopupProvider> <PopupProvider>
<BoardProvider> <Component {...pageProps} />
<Component {...pageProps} />
</BoardProvider>
</PopupProvider> </PopupProvider>
</ModalProvider> </ModalProvider>
</ThemeProvider> </ThemeProvider>

View File

@@ -1,105 +0,0 @@
import type { ReactNode } from "react";
import React, { createContext, useContext, useState } from "react";
import type { GetBoardByIdOutput, NewListInput } from "@kan/api/types";
import { generateUID } from "@kan/shared/utils";
import { usePopup } from "~/providers/popup";
import { api } from "~/utils/api";
interface BoardContextProps {
boardData: GetBoardByIdOutput;
setBoardData: React.Dispatch<React.SetStateAction<GetBoardByIdOutput>>;
addList: (params: NewListInput) => void;
removeCard: (params: { cardPublicId: string }) => void;
refetchBoard: () => Promise<void>;
}
const initialBoardData: GetBoardByIdOutput = {
name: "",
publicId: "",
lists: [],
labels: [],
workspace: {
publicId: "",
members: [],
},
};
const BoardContext = createContext<BoardContextProps | undefined>(undefined);
export const BoardProvider: React.FC<{ children: ReactNode }> = ({
children,
}) => {
const utils = api.useUtils();
const [boardData, setBoardData] =
useState<GetBoardByIdOutput>(initialBoardData);
const { showPopup } = usePopup();
const refetchBoard = async () => {
if (!boardData?.publicId) return;
try {
await utils.board.byId.refetch();
} catch (e) {
showPopup({
header: "Error fetching board",
message: "Please try again later, or contact customer support.",
icon: "error",
});
}
};
const addList = ({ name, boardPublicId }: NewListInput) => {
if (!boardData) return;
const newList = {
publicId: generateUID(),
name,
boardId: 1,
boardPublicId,
cards: [],
index: boardData.lists.length,
};
const updatedLists = [...boardData.lists, newList];
setBoardData({ ...boardData, lists: updatedLists });
};
const removeCard = ({ cardPublicId }: { cardPublicId: string }) => {
if (!boardData) return;
const updatedLists = boardData.lists.map((list) => {
const updatedCards = list.cards.filter(
(card) => card.publicId !== cardPublicId,
);
return { ...list, cards: updatedCards };
});
setBoardData({ ...boardData, lists: updatedLists });
};
return (
<BoardContext.Provider
value={{
boardData,
setBoardData,
addList,
removeCard,
refetchBoard,
}}
>
{children}
</BoardContext.Provider>
);
};
export const useBoard = () => {
const context = useContext(BoardContext);
if (context === undefined) {
throw new Error("useBoard must be used within a BoardProvider");
}
return context;
};

View File

@@ -3,11 +3,12 @@ import { HiEllipsisHorizontal, HiLink, HiOutlineTrash } from "react-icons/hi2";
import Dropdown from "~/components/Dropdown"; import Dropdown from "~/components/Dropdown";
import { useModal } from "~/providers/modal"; import { useModal } from "~/providers/modal";
export default function BoardDropdown() { export default function BoardDropdown({ isLoading }: { isLoading: boolean }) {
const { openModal } = useModal(); const { openModal } = useModal();
return ( return (
<Dropdown <Dropdown
disabled={isLoading}
items={[ items={[
{ {
label: "Edit board URL", label: "Edit board URL",

View File

@@ -1,14 +1,15 @@
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { api } from "~/utils/api";
import { useBoard } from "~/providers/board";
import { useModal } from "~/providers/modal";
import Button from "~/components/Button"; import Button from "~/components/Button";
import { useModal } from "~/providers/modal";
import { api } from "~/utils/api";
export function DeleteBoardConfirmation() { export function DeleteBoardConfirmation({
boardPublicId,
}: {
boardPublicId: string;
}) {
const router = useRouter(); const router = useRouter();
const { boardData } = useBoard();
const { closeModal } = useModal(); const { closeModal } = useModal();
const deleteBoard = api.board.delete.useMutation({ const deleteBoard = api.board.delete.useMutation({
@@ -19,9 +20,9 @@ export function DeleteBoardConfirmation() {
}); });
const handleDeleteBoard = () => { const handleDeleteBoard = () => {
if (boardData?.publicId) if (boardPublicId)
deleteBoard.mutate({ deleteBoard.mutate({
boardPublicId: boardData.publicId, boardPublicId: boardPublicId,
}); });
}; };
@@ -39,7 +40,9 @@ export function DeleteBoardConfirmation() {
<Button onClick={() => closeModal()} variant="secondary"> <Button onClick={() => closeModal()} variant="secondary">
Cancel Cancel
</Button> </Button>
<Button onClick={handleDeleteBoard}>Delete</Button> <Button onClick={handleDeleteBoard} isLoading={deleteBoard.isPending}>
Delete
</Button>
</div> </div>
</div> </div>
); );

View File

@@ -1,45 +1,39 @@
import Button from "~/components/Button"; import Button from "~/components/Button";
import { useBoard } from "~/providers/board";
import { useModal } from "~/providers/modal"; import { useModal } from "~/providers/modal";
import { usePopup } from "~/providers/popup"; import { usePopup } from "~/providers/popup";
import { api } from "~/utils/api"; import { api } from "~/utils/api";
interface DeleteListConfirmationProps { interface DeleteListConfirmationProps {
listPublicId: string; listPublicId: string;
queryParams: QueryParams;
}
interface QueryParams {
boardPublicId: string;
members: string[];
labels: string[];
} }
export function DeleteListConfirmation({ export function DeleteListConfirmation({
listPublicId, listPublicId,
queryParams,
}: DeleteListConfirmationProps) { }: DeleteListConfirmationProps) {
const utils = api.useUtils(); const utils = api.useUtils();
const { boardData } = useBoard();
const { closeModal } = useModal(); const { closeModal } = useModal();
const { showPopup } = usePopup(); const { showPopup } = usePopup();
const refetchBoard = async () => {
if (boardData?.publicId) {
try {
await utils.board.byId.refetch();
} catch (e) {
console.error(e);
}
}
};
const deleteList = api.list.delete.useMutation({ const deleteList = api.list.delete.useMutation({
onSuccess: () => { onError: () => {
closeModal();
return refetchBoard();
},
onError: async () => {
closeModal();
await refetchBoard();
showPopup({ showPopup({
header: "Unable to delete list", header: "Unable to delete list",
message: "Please try again later, or contact customer support.", message: "Please try again later, or contact customer support.",
icon: "error", icon: "error",
}); });
}, },
onSettled: async () => {
closeModal();
await utils.board.byId.invalidate(queryParams);
},
}); });
return ( return (

View File

@@ -62,9 +62,11 @@ interface BoardData {
const Filters = ({ const Filters = ({
position = "right", position = "right",
boardData, boardData,
isLoading,
}: { }: {
position?: "left" | "right"; position?: "left" | "right";
boardData: BoardData | null; boardData: BoardData | null;
isLoading: boolean;
}) => { }) => {
const router = useRouter(); const router = useRouter();
@@ -166,7 +168,11 @@ const Filters = ({
menuSpacing="md" menuSpacing="md"
position={position} position={position}
> >
<Button variant="secondary" iconLeft={<IoFilterOutline />}> <Button
variant="secondary"
disabled={isLoading}
iconLeft={<IoFilterOutline />}
>
Filter Filter
</Button> </Button>
{numOfFilters > 0 && ( {numOfFilters > 0 && (

View File

@@ -86,11 +86,11 @@ export function NewCardForm({
listId: 2, listId: 2,
description: "", description: "",
labels: oldBoard.labels.filter((label) => labels: oldBoard.labels.filter((label) =>
labelPublicIds.includes(label.publicId), args.labelPublicIds.includes(label.publicId),
), ),
members: members:
oldBoard.workspace?.members.filter((member) => oldBoard.workspace?.members.filter((member) =>
memberPublicIds.includes(member.publicId), args.memberPublicIds.includes(member.publicId),
) ?? [], ) ?? [],
_filteredLabels: labelPublicIds.map((id) => ({ publicId: id })), _filteredLabels: labelPublicIds.map((id) => ({ publicId: id })),
_filteredMembers: memberPublicIds.map((id) => ({ publicId: id })), _filteredMembers: memberPublicIds.map((id) => ({ publicId: id })),

View File

@@ -3,11 +3,11 @@ import { useForm } from "react-hook-form";
import { HiXMark } from "react-icons/hi2"; import { HiXMark } from "react-icons/hi2";
import type { NewListInput } from "@kan/api/types"; import type { NewListInput } from "@kan/api/types";
import { generateUID } from "@kan/shared/utils";
import Button from "~/components/Button"; import Button from "~/components/Button";
import Input from "~/components/Input"; import Input from "~/components/Input";
import Toggle from "~/components/Toggle"; import Toggle from "~/components/Toggle";
import { useBoard } from "~/providers/board";
import { useModal } from "~/providers/modal"; import { useModal } from "~/providers/modal";
import { usePopup } from "~/providers/popup"; import { usePopup } from "~/providers/popup";
import { api } from "~/utils/api"; import { api } from "~/utils/api";
@@ -16,11 +16,24 @@ type NewListFormInput = NewListInput & {
isCreateAnotherEnabled: boolean; isCreateAnotherEnabled: boolean;
}; };
export function NewListForm({ boardPublicId }: { boardPublicId: string }) { interface QueryParams {
const { refetchBoard, addList } = useBoard(); boardPublicId: string;
members: string[];
labels: string[];
}
export function NewListForm({
boardPublicId,
queryParams,
}: {
boardPublicId: string;
queryParams: QueryParams;
}) {
const { closeModal } = useModal(); const { closeModal } = useModal();
const { showPopup } = usePopup(); const { showPopup } = usePopup();
const utils = api.useUtils();
const { register, handleSubmit, reset, setValue, watch } = const { register, handleSubmit, reset, setValue, watch } =
useForm<NewListFormInput>({ useForm<NewListFormInput>({
defaultValues: { defaultValues: {
@@ -33,18 +46,41 @@ export function NewListForm({ boardPublicId }: { boardPublicId: string }) {
const isCreateAnotherEnabled = watch("isCreateAnotherEnabled"); const isCreateAnotherEnabled = watch("isCreateAnotherEnabled");
const createList = api.list.create.useMutation({ const createList = api.list.create.useMutation({
onSuccess: async () => { onMutate: async (args) => {
await refetchBoard(); await utils.board.byId.cancel();
const currentState = utils.board.byId.getData(queryParams);
utils.board.byId.setData(queryParams, (oldBoard) => {
if (!oldBoard) return oldBoard;
const newList = {
publicId: generateUID(),
name: args.name,
boardId: 1,
boardPublicId,
cards: [],
index: oldBoard.lists.length,
};
const updatedLists = [...oldBoard.lists, newList];
return { ...oldBoard, lists: updatedLists };
});
return { previousState: currentState };
}, },
onError: async () => { onError: (_error, _newList, context) => {
closeModal(); utils.board.byId.setData(queryParams, context?.previousState);
await refetchBoard();
showPopup({ showPopup({
header: "Unable to create list", header: "Unable to create list",
message: "Please try again later, or contact customer support.", message: "Please try again later, or contact customer support.",
icon: "error", icon: "error",
}); });
}, },
onSettled: async () => {
await utils.board.byId.invalidate(queryParams);
},
}); });
useEffect(() => { useEffect(() => {
@@ -54,7 +90,6 @@ export function NewListForm({ boardPublicId }: { boardPublicId: string }) {
}, []); }, []);
const onSubmit = (data: NewListInput) => { const onSubmit = (data: NewListInput) => {
addList(data);
const isCreateAnotherEnabled = watch("isCreateAnotherEnabled"); const isCreateAnotherEnabled = watch("isCreateAnotherEnabled");
if (!isCreateAnotherEnabled) closeModal(); if (!isCreateAnotherEnabled) closeModal();
reset({ reset({

View File

@@ -6,7 +6,6 @@ import { z } from "zod";
import Button from "~/components/Button"; import Button from "~/components/Button";
import Input from "~/components/Input"; import Input from "~/components/Input";
import { useBoard } from "~/providers/board";
import { useModal } from "~/providers/modal"; import { useModal } from "~/providers/modal";
import { usePopup } from "~/providers/popup"; import { usePopup } from "~/providers/popup";
import { api } from "~/utils/api"; import { api } from "~/utils/api";
@@ -25,18 +24,26 @@ const schema = z.object({
type FormValues = z.infer<typeof schema>; type FormValues = z.infer<typeof schema>;
interface QueryParams {
boardPublicId: string;
members: string[];
labels: string[];
}
export function UpdateBoardSlugForm({ export function UpdateBoardSlugForm({
boardPublicId, boardPublicId,
workspaceSlug, workspaceSlug,
boardSlug, boardSlug,
queryParams,
}: { }: {
boardPublicId: string; boardPublicId: string;
workspaceSlug: string; workspaceSlug: string;
boardSlug: string; boardSlug: string;
queryParams: QueryParams;
}) { }) {
const { closeModal } = useModal(); const { closeModal } = useModal();
const { showPopup } = usePopup(); const { showPopup } = usePopup();
const { refetchBoard } = useBoard(); const utils = api.useUtils();
const { const {
register, register,
@@ -51,18 +58,17 @@ export function UpdateBoardSlugForm({
}); });
const updateBoardSlug = api.board.update.useMutation({ const updateBoardSlug = api.board.update.useMutation({
onSuccess: async () => {
await refetchBoard();
closeModal();
},
onError: () => { onError: () => {
closeModal();
showPopup({ showPopup({
header: "Unable to update board URL", header: "Unable to update board URL",
message: "Please try again later, or contact customer support.", message: "Please try again later, or contact customer support.",
icon: "error", icon: "error",
}); });
}, },
onSettled: async () => {
closeModal();
await utils.board.byId.invalidate(queryParams);
},
}); });
useEffect(() => { useEffect(() => {

View File

@@ -2,19 +2,28 @@ import { useEffect, useState } from "react";
import { HiOutlineEye, HiOutlineEyeSlash } from "react-icons/hi2"; import { HiOutlineEye, HiOutlineEyeSlash } from "react-icons/hi2";
import Button from "~/components/Button"; import Button from "~/components/Button";
import { useBoard } from "~/providers/board";
import { usePopup } from "~/providers/popup"; import { usePopup } from "~/providers/popup";
import { api } from "~/utils/api"; import { api } from "~/utils/api";
interface QueryParams {
boardPublicId: string;
members: string[];
labels: string[];
}
const VisibilityButton = ({ const VisibilityButton = ({
visibility, visibility,
boardPublicId, boardPublicId,
queryParams,
isLoading,
}: { }: {
visibility: "public" | "private"; visibility: "public" | "private";
boardPublicId: string; boardPublicId: string;
queryParams: QueryParams;
isLoading: boolean;
}) => { }) => {
const { refetchBoard } = useBoard();
const { showPopup } = usePopup(); const { showPopup } = usePopup();
const utils = api.useUtils();
const [stateVisibility, setStateVisibility] = useState<"public" | "private">( const [stateVisibility, setStateVisibility] = useState<"public" | "private">(
visibility, visibility,
); );
@@ -26,8 +35,7 @@ const VisibilityButton = ({
const isPublic = stateVisibility === "public"; const isPublic = stateVisibility === "public";
const updateBoardVisibility = api.board.update.useMutation({ const updateBoardVisibility = api.board.update.useMutation({
onSuccess: async () => { onSuccess: () => {
await refetchBoard();
setStateVisibility(isPublic ? "private" : "public"); setStateVisibility(isPublic ? "private" : "public");
}, },
onError: () => { onError: () => {
@@ -37,6 +45,9 @@ const VisibilityButton = ({
icon: "error", icon: "error",
}); });
}, },
onSettled: async () => {
await utils.board.byId.invalidate(queryParams);
},
}); });
const handleUpdateBoardVisibility = () => { const handleUpdateBoardVisibility = () => {
@@ -52,6 +63,7 @@ const VisibilityButton = ({
onClick={handleUpdateBoardVisibility} onClick={handleUpdateBoardVisibility}
iconLeft={isPublic ? <HiOutlineEye /> : <HiOutlineEyeSlash />} iconLeft={isPublic ? <HiOutlineEye /> : <HiOutlineEyeSlash />}
isLoading={updateBoardVisibility.isPending} isLoading={updateBoardVisibility.isPending}
disabled={isLoading}
> >
{isPublic ? "Public" : "Private"} {isPublic ? "Public" : "Private"}
</Button> </Button>

View File

@@ -42,6 +42,7 @@ export default function BoardPage() {
const { openModal, modalContentType } = useModal(); const { openModal, modalContentType } = useModal();
const [selectedPublicListId, setSelectedPublicListId] = const [selectedPublicListId, setSelectedPublicListId] =
useState<PublicListId>(""); useState<PublicListId>("");
const [isInitialLoading, setIsInitialLoading] = useState(true);
const boardId = params?.boardId.length ? params.boardId[0] : null; const boardId = params?.boardId.length ? params.boardId[0] : null;
@@ -70,11 +71,19 @@ export default function BoardPage() {
const { const {
data: boardData, data: boardData,
isSuccess, isSuccess,
isLoading, isLoading: isQueryLoading,
} = api.board.byId.useQuery(queryParams, { } = api.board.byId.useQuery(queryParams, {
enabled: !!boardId, enabled: !!boardId,
}); });
useEffect(() => {
if (boardId) {
setIsInitialLoading(false);
}
}, [boardId]);
const isLoading = isInitialLoading || isQueryLoading;
const updateListMutation = api.list.reorder.useMutation({ const updateListMutation = api.list.reorder.useMutation({
onMutate: async (args) => { onMutate: async (args) => {
await utils.board.byId.cancel(); await utils.board.byId.cancel();
@@ -166,8 +175,6 @@ export default function BoardPage() {
} }
}, [isSuccess, boardData, setValue]); }, [isSuccess, boardData, setValue]);
if (!boardId || !boardData) return <></>;
const openNewListForm = (publicBoardId: string) => { const openNewListForm = (publicBoardId: string) => {
openModal("NEW_LIST"); openModal("NEW_LIST");
setSelectedPublicListId(publicBoardId); setSelectedPublicListId(publicBoardId);
@@ -205,7 +212,7 @@ export default function BoardPage() {
return ( return (
<> <>
<PageHead <PageHead
title={`${boardData.name ?? "Board"} | ${workspace.name ?? "Workspace"}`} title={`${boardData?.name ?? "Board"} | ${workspace.name ?? "Workspace"}`}
/> />
<div className="relative flex h-full flex-col"> <div className="relative flex h-full flex-col">
<PatternedBackground /> <PatternedBackground />
@@ -231,10 +238,16 @@ export default function BoardPage() {
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-2">
<VisibilityButton <VisibilityButton
visibility={boardData.visibility} visibility={boardData?.visibility ?? "private"}
boardPublicId={boardId} boardPublicId={boardId ?? ""}
queryParams={queryParams}
isLoading={isLoading}
/>
<Filters
boardData={boardData ?? null}
position="left"
isLoading={isLoading}
/> />
<Filters boardData={boardData} position="left" />
<Button <Button
iconLeft={ iconLeft={
<HiOutlinePlusSmall <HiOutlinePlusSmall
@@ -242,11 +255,14 @@ export default function BoardPage() {
aria-hidden="true" aria-hidden="true"
/> />
} }
onClick={() => openNewListForm(boardId)} onClick={() => {
if (boardId) openNewListForm(boardId);
}}
disabled={isLoading}
> >
New list New list
</Button> </Button>
<BoardDropdown /> <BoardDropdown isLoading={isLoading} />
</div> </div>
</div> </div>
@@ -271,7 +287,7 @@ export default function BoardPage() {
{...provided.droppableProps} {...provided.droppableProps}
> >
<div className="min-w-[2rem]" /> <div className="min-w-[2rem]" />
{boardData.lists.map((list, index) => ( {boardData?.lists.map((list, index) => (
<List <List
index={index} index={index}
key={index} key={index}
@@ -338,26 +354,35 @@ export default function BoardPage() {
)} )}
</div> </div>
<Modal modalSize={modalContentType === "NEW_CARD" ? "md" : "sm"}> <Modal modalSize={modalContentType === "NEW_CARD" ? "md" : "sm"}>
{modalContentType === "DELETE_BOARD" && <DeleteBoardConfirmation />} {modalContentType === "DELETE_BOARD" && (
<DeleteBoardConfirmation boardPublicId={boardId ?? ""} />
)}
{modalContentType === "DELETE_LIST" && ( {modalContentType === "DELETE_LIST" && (
<DeleteListConfirmation listPublicId={selectedPublicListId} /> <DeleteListConfirmation
listPublicId={selectedPublicListId}
queryParams={queryParams}
/>
)} )}
{modalContentType === "NEW_CARD" && ( {modalContentType === "NEW_CARD" && (
<NewCardForm <NewCardForm
boardPublicId={boardId} boardPublicId={boardId ?? ""}
listPublicId={selectedPublicListId} listPublicId={selectedPublicListId}
queryParams={queryParams} queryParams={queryParams}
/> />
)} )}
{modalContentType === "NEW_LIST" && ( {modalContentType === "NEW_LIST" && (
<NewListForm boardPublicId={boardId} /> <NewListForm
boardPublicId={boardId ?? ""}
queryParams={queryParams}
/>
)} )}
{modalContentType === "NEW_WORKSPACE" && <NewWorkspaceForm />} {modalContentType === "NEW_WORKSPACE" && <NewWorkspaceForm />}
{modalContentType === "UPDATE_BOARD_SLUG" && ( {modalContentType === "UPDATE_BOARD_SLUG" && (
<UpdateBoardSlugForm <UpdateBoardSlugForm
boardPublicId={boardId} boardPublicId={boardId ?? ""}
workspaceSlug={workspace.slug} workspaceSlug={workspace.slug ?? ""}
boardSlug={boardData.slug} boardSlug={boardData?.slug ?? ""}
queryParams={queryParams}
/> />
)} )}
</Modal> </Modal>

View File

@@ -1,6 +1,6 @@
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useBoard } from "~/providers/board"; import Button from "~/components/Button";
import { useModal } from "~/providers/modal"; import { useModal } from "~/providers/modal";
import { usePopup } from "~/providers/popup"; import { usePopup } from "~/providers/popup";
import { api } from "~/utils/api"; import { api } from "~/utils/api";
@@ -15,26 +15,53 @@ export function DeleteCardConfirmation({
boardPublicId, boardPublicId,
}: DeleteCardConfirmationProps) { }: DeleteCardConfirmationProps) {
const { closeModal } = useModal(); const { closeModal } = useModal();
const utils = api.useUtils();
const router = useRouter(); const router = useRouter();
const { removeCard, refetchBoard } = useBoard();
const { showPopup } = usePopup(); const { showPopup } = usePopup();
const queryParams = {
boardPublicId,
};
const deleteCardMutation = api.card.delete.useMutation({ const deleteCardMutation = api.card.delete.useMutation({
onSuccess: () => refetchBoard(), onMutate: async (args) => {
onError: () => await utils.board.byId.cancel();
const currentState = utils.board.byId.getData(queryParams);
utils.board.byId.setData(queryParams, (oldBoard) => {
if (!oldBoard) return oldBoard;
const updatedLists = oldBoard.lists.map((list) => {
const updatedCards = list.cards.filter(
(card) => card.publicId !== args.cardPublicId,
);
return { ...list, cards: updatedCards };
});
return { ...oldBoard, lists: updatedLists };
});
return { previousState: currentState };
},
onError: (_error, _newList, context) => {
utils.board.byId.setData(queryParams, context?.previousState);
showPopup({ showPopup({
header: "Error deleting card", header: "Unable to delete card",
message: "Please try again later, or contact customer support.", message: "Please try again later, or contact customer support.",
icon: "error", icon: "error",
}), });
},
onSuccess: () => {
router.push(`/boards/${boardPublicId}`);
},
onSettled: async () => {
closeModal();
await utils.board.byId.invalidate(queryParams);
},
}); });
const handleDeleteCard = () => { const handleDeleteCard = () => {
removeCard({
cardPublicId,
});
closeModal();
router.push(`/boards/${boardPublicId}`);
deleteCardMutation.mutate({ deleteCardMutation.mutate({
cardPublicId, cardPublicId,
}); });
@@ -57,12 +84,12 @@ export function DeleteCardConfirmation({
> >
Cancel Cancel
</button> </button>
<button <Button
onClick={handleDeleteCard} onClick={handleDeleteCard}
className="inline-flex justify-center rounded-md bg-light-1000 px-3 py-2 text-sm font-semibold text-light-50 shadow-sm focus-visible:outline-none dark:bg-dark-1000 dark:text-dark-50" isLoading={deleteCardMutation.isPending}
> >
Delete Delete
</button> </Button>
</div> </div>
</div> </div>
); );