perf: improve optimistic updates

This commit is contained in:
Henry
2025-02-05 22:22:36 +00:00
parent 3ba600bc41
commit b1fa8a529d
6 changed files with 129 additions and 136 deletions

View File

@@ -1,11 +1,12 @@
import type { CreateTRPCClientOptions, TRPCLink } from "@trpc/client"; import type { TRPCLink } from "@trpc/client";
import type { inferRouterInputs, inferRouterOutputs } from "@trpc/server";
import { QueryClient } from "@tanstack/react-query";
import { httpBatchLink, loggerLink } from "@trpc/client"; import { httpBatchLink, loggerLink } from "@trpc/client";
import { createTRPCNext } from "@trpc/next"; import { createTRPCNext } from "@trpc/next";
import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server";
import { observable } from "@trpc/server/observable"; import { observable } from "@trpc/server/observable";
import superjson from "superjson"; import superjson from "superjson";
import { type AppRouter } from "@kan/api/root"; import type { AppRouter } from "@kan/api/root";
/** /**
* This is the client-side entrypoint for your tRPC API. It is used to create the `api` object which * This is the client-side entrypoint for your tRPC API. It is used to create the `api` object which
@@ -42,6 +43,8 @@ const getBaseUrl = () => {
return `http://localhost:${process.env.PORT ?? 3000}`; // dev SSR should use localhost return `http://localhost:${process.env.PORT ?? 3000}`; // dev SSR should use localhost
}; };
const queryClient = new QueryClient();
// @ts-expect-error // @ts-expect-error
export const api = createTRPCNext<AppRouter>({ export const api = createTRPCNext<AppRouter>({
config() { config() {
@@ -58,6 +61,7 @@ export const api = createTRPCNext<AppRouter>({
transformer: superjson, transformer: superjson,
}), }),
], ],
queryClient: queryClient,
}; };
}, },
ssr: false, ssr: false,

View File

@@ -15,33 +15,67 @@ interface LabelSelectorProps {
selected: boolean; selected: boolean;
leftIcon: React.ReactNode; leftIcon: React.ReactNode;
}[]; }[];
refetchCard: () => Promise<void>;
handleSelectLabel: (labelPublicId: string) => void;
isLoading: boolean; isLoading: boolean;
} }
export default function LabelSelector({ export default function LabelSelector({
cardPublicId, cardPublicId,
labels, labels,
refetchCard,
handleSelectLabel,
isLoading, isLoading,
}: LabelSelectorProps) { }: LabelSelectorProps) {
const utils = api.useUtils();
const { openModal } = useModal(); const { openModal } = useModal();
const { showPopup } = usePopup(); const { showPopup } = usePopup();
const addOrRemoveLabel = api.card.addOrRemoveLabel.useMutation({ const addOrRemoveLabel = api.card.addOrRemoveLabel.useMutation({
onSuccess: async () => { onMutate: async (update) => {
await refetchCard(); await utils.card.byId.cancel();
const previousCard = utils.card.byId.getData({ cardPublicId });
utils.card.byId.setData({ cardPublicId }, (oldCard) => {
if (!oldCard) return oldCard;
const hasLabel = oldCard.labels.some(
(label) => label.publicId === update.labelPublicId,
);
const labelToAdd = oldCard.labels.find(
(label) => label.publicId === update.labelPublicId,
);
const updatedLabels = hasLabel
? oldCard.labels.filter(
(label) => label.publicId !== update.labelPublicId,
)
: [
...oldCard.labels,
{
publicId: update.labelPublicId,
name: labelToAdd?.name ?? "",
colourCode: labelToAdd?.colourCode ?? "",
},
];
return {
...oldCard,
labels: updatedLabels,
};
});
return { previousCard };
}, },
onError: async () => { onError: (_error, _newList, context) => {
await refetchCard(); utils.card.byId.setData({ cardPublicId }, context?.previousCard);
showPopup({ showPopup({
header: "Unable to update labels", header: "Unable to update labels",
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.card.byId.invalidate({ cardPublicId });
},
}); });
const selectedLabels = labels.filter((label) => label.selected); const selectedLabels = labels.filter((label) => label.selected);
@@ -56,7 +90,6 @@ export default function LabelSelector({
<CheckboxDropdown <CheckboxDropdown
items={labels} items={labels}
handleSelect={(_, label) => { handleSelect={(_, label) => {
handleSelectLabel(label.key);
addOrRemoveLabel.mutate({ cardPublicId, labelPublicId: label.key }); addOrRemoveLabel.mutate({ cardPublicId, labelPublicId: label.key });
}} }}
handleEdit={(labelPublicId) => openModal("EDIT_LABEL", labelPublicId)} handleEdit={(labelPublicId) => openModal("EDIT_LABEL", labelPublicId)}

View File

@@ -11,32 +11,51 @@ interface ListSelectorProps {
value: string; value: string;
selected: boolean; selected: boolean;
}[]; }[];
refetchCard: () => Promise<void>;
handleChangeList: (newListPublicId: string, newListName: string) => void;
isLoading: boolean; isLoading: boolean;
} }
export default function ListSelector({ export default function ListSelector({
cardPublicId, cardPublicId,
lists, lists,
handleChangeList,
refetchCard,
isLoading, isLoading,
}: ListSelectorProps) { }: ListSelectorProps) {
const utils = api.useUtils();
const { showPopup } = usePopup(); const { showPopup } = usePopup();
const updateCardList = api.card.reorder.useMutation({ const updateCardList = api.card.reorder.useMutation({
onSuccess: async () => { onMutate: async (newList) => {
await refetchCard(); await utils.card.byId.cancel();
const previousCard = utils.card.byId.getData({ cardPublicId });
utils.card.byId.setData({ cardPublicId }, (oldCard) => {
if (!oldCard) return oldCard;
return {
...oldCard,
list: {
...oldCard.list,
publicId: newList.newListPublicId,
name: oldCard.list?.name ?? "",
board: oldCard.list?.board ?? null,
},
};
});
return { previousCard };
}, },
onError: async () => { onError: (_error, _newList, context) => {
await refetchCard(); utils.card.byId.setData({ cardPublicId }, context?.previousCard);
showPopup({ showPopup({
header: "Unable to update list", header: "Unable to update 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.card.byId.invalidate({ cardPublicId });
},
}); });
const selectedList = lists.find((list) => list.selected); const selectedList = lists.find((list) => list.selected);
@@ -51,7 +70,6 @@ export default function ListSelector({
<CheckboxDropdown <CheckboxDropdown
items={lists} items={lists}
handleSelect={(_, member) => { handleSelect={(_, member) => {
handleChangeList(member.key, member.value);
updateCardList.mutate({ updateCardList.mutate({
cardPublicId, cardPublicId,
newListPublicId: member.key, newListPublicId: member.key,

View File

@@ -17,34 +17,70 @@ interface MemberSelectorProps {
leftIcon: React.ReactNode; leftIcon: React.ReactNode;
imageUrl: string | undefined; imageUrl: string | undefined;
}[]; }[];
handleSelectMember: (memberPublicId: string) => void;
refetchCard: () => Promise<void>;
isLoading: boolean; isLoading: boolean;
} }
export default function MemberSelector({ export default function MemberSelector({
cardPublicId, cardPublicId,
members, members,
handleSelectMember,
refetchCard,
isLoading, isLoading,
}: MemberSelectorProps) { }: MemberSelectorProps) {
const router = useRouter(); const router = useRouter();
const utils = api.useUtils();
const { openModal } = useModal(); const { openModal } = useModal();
const { showPopup } = usePopup(); const { showPopup } = usePopup();
const addOrRemoveMember = api.card.addOrRemoveMember.useMutation({ const addOrRemoveMember = api.card.addOrRemoveMember.useMutation({
onSuccess: async () => { onMutate: async (update) => {
await refetchCard(); await utils.card.byId.cancel();
const previousCard = utils.card.byId.getData({ cardPublicId });
utils.card.byId.setData({ cardPublicId }, (oldCard) => {
if (!oldCard) return oldCard;
const hasMember = oldCard.members.some(
(member) => member.publicId === update.workspaceMemberPublicId,
);
const memberToAdd = oldCard.members.find(
(member) => member.publicId === update.workspaceMemberPublicId,
);
const updatedMembers = hasMember
? oldCard.members.filter(
(member) => member.publicId !== update.workspaceMemberPublicId,
)
: [
...oldCard.members,
{
publicId: update.workspaceMemberPublicId,
user: {
id: memberToAdd?.user?.id ?? "",
name: memberToAdd?.user?.name ?? "",
},
},
];
return {
...oldCard,
members: updatedMembers,
};
});
return { previousCard };
}, },
onError: async () => { onError: (_error, _newList, context) => {
await refetchCard(); utils.card.byId.setData({ cardPublicId }, context?.previousCard);
showPopup({ showPopup({
header: "Unable to update members", header: "Unable to update members",
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.card.byId.invalidate({ cardPublicId });
},
}); });
const selectedMembers = members.filter((member) => member.selected); const selectedMembers = members.filter((member) => member.selected);
@@ -64,7 +100,6 @@ export default function MemberSelector({
<CheckboxDropdown <CheckboxDropdown
items={members} items={members}
handleSelect={(_, member) => { handleSelect={(_, member) => {
handleSelectMember(member.key);
addOrRemoveMember.mutate({ addOrRemoveMember.mutate({
cardPublicId, cardPublicId,
workspaceMemberPublicId: member.key, workspaceMemberPublicId: member.key,

View File

@@ -1,12 +1,9 @@
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import ContentEditable from "react-contenteditable"; import ContentEditable from "react-contenteditable";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { IoChevronForwardSharp } from "react-icons/io5"; import { IoChevronForwardSharp } from "react-icons/io5";
import type { GetCardByIdOutput } from "@kan/api/types";
import Avatar from "~/components/Avatar"; import Avatar from "~/components/Avatar";
import LabelIcon from "~/components/LabelIcon"; import LabelIcon from "~/components/LabelIcon";
import Modal from "~/components/modal"; import Modal from "~/components/modal";
@@ -38,30 +35,15 @@ export default function CardPage() {
const utils = api.useUtils(); const utils = api.useUtils();
const { modalContentType, entityId } = useModal(); const { modalContentType, entityId } = useModal();
const { showPopup } = usePopup(); const { showPopup } = usePopup();
const [card, setCard] = useState<GetCardByIdOutput>();
const cardId = Array.isArray(router.query.cardId) const cardId = Array.isArray(router.query.cardId)
? router.query.cardId[0] ? router.query.cardId[0]
: router.query.cardId; : router.query.cardId;
const { data, isLoading, refetch } = api.card.byId.useQuery({ const { data: card, isLoading } = api.card.byId.useQuery({
cardPublicId: cardId ?? "", cardPublicId: cardId ?? "",
}); });
const refetchCard = async () => {
try {
const { data: updatedCard } = await refetch();
if (updatedCard) setCard(updatedCard);
} catch (error) {
console.error({ error });
}
};
useEffect(() => {
setCard(data);
}, [data]);
const board = card?.list?.board; const board = card?.list?.board;
const boardId = board?.publicId; const boardId = board?.publicId;
const labels = board?.labels; const labels = board?.labels;
@@ -70,74 +52,6 @@ export default function CardPage() {
const selectedLabels = card?.labels; const selectedLabels = card?.labels;
const selectedMembers = card?.members; const selectedMembers = card?.members;
const handleChangeList = (newListPublicId: string) => {
if (!card) return;
setCard({
...card,
list: {
...card.list,
publicId: newListPublicId,
name: card.list?.name ?? "",
board: card.list?.board ?? null,
},
});
};
const handleSelectLabel = (labelPublicId: string) => {
if (!card) return;
const isSelected = card.labels.some(
(label) => label.publicId === labelPublicId,
);
const updatedLabels = isSelected
? card.labels.filter((label) => label.publicId !== labelPublicId)
: [
...(card.labels ?? []),
labels?.find((label) => label.publicId === labelPublicId),
].filter(Boolean);
setCard({
...card,
labels: updatedLabels as {
publicId: string;
name: string;
colourCode: string | null;
}[],
});
};
const handleSelectMember = (memberPublicId: string) => {
if (!card) return;
const isSelected = card.members.some(
(member) => member.publicId === memberPublicId,
);
const updatedMembers = isSelected
? card.members.filter((member) => member.publicId !== memberPublicId)
: [
...(card.members ?? []),
workspaceMembers?.find(
(member) => member.publicId === memberPublicId,
),
];
setCard({
...card,
members: updatedMembers.filter(Boolean) as {
publicId: string;
user: {
id: string;
name: string | null;
email: string;
image: string | null;
} | null;
}[],
});
};
const formattedLabels = const formattedLabels =
labels?.map((label) => { labels?.map((label) => {
const isSelected = selectedLabels?.some( const isSelected = selectedLabels?.some(
@@ -189,25 +103,23 @@ export default function CardPage() {
}) ?? []; }) ?? [];
const updateCard = api.card.update.useMutation({ const updateCard = api.card.update.useMutation({
onSuccess: async () => { onError: () => {
await refetchCard();
},
onError: async () => {
await refetchCard();
showPopup({ showPopup({
header: "Unable to update card", header: "Unable to update card",
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.card.byId.invalidate({ cardPublicId: cardId });
},
}); });
const { register, handleSubmit, setValue, watch } = useForm<FormValues>({ const { register, handleSubmit, setValue, watch } = useForm<FormValues>({
values: { values: {
cardId: cardId ?? "", cardId: cardId ?? "",
title: data?.title ?? "", title: card?.title ?? "",
description: data?.description ?? "", description: card?.description ?? "",
}, },
}); });
@@ -224,7 +136,7 @@ export default function CardPage() {
return ( return (
<> <>
<PageHead <PageHead
title={`${data?.title ?? "Card"} | ${board?.name ?? "Board"}`} title={`${card?.title ?? "Card"} | ${board?.name ?? "Board"}`}
/> />
<div className="flex h-full flex-1 flex-row"> <div className="flex h-full flex-1 flex-row">
<div className="flex h-full w-full flex-col overflow-hidden"> <div className="flex h-full w-full flex-col overflow-hidden">
@@ -307,8 +219,6 @@ export default function CardPage() {
<ListSelector <ListSelector
cardPublicId={cardId} cardPublicId={cardId}
lists={formattedLists} lists={formattedLists}
refetchCard={refetchCard}
handleChangeList={handleChangeList}
isLoading={isLoading} isLoading={isLoading}
/> />
</div> </div>
@@ -317,8 +227,6 @@ export default function CardPage() {
<LabelSelector <LabelSelector
cardPublicId={cardId} cardPublicId={cardId}
labels={formattedLabels} labels={formattedLabels}
refetchCard={refetchCard}
handleSelectLabel={handleSelectLabel}
isLoading={isLoading} isLoading={isLoading}
/> />
</div> </div>
@@ -327,8 +235,6 @@ export default function CardPage() {
<MemberSelector <MemberSelector
cardPublicId={cardId} cardPublicId={cardId}
members={formattedMembers} members={formattedMembers}
refetchCard={refetchCard}
handleSelectMember={handleSelectMember}
isLoading={isLoading} isLoading={isLoading}
/> />
</div> </div>

View File

@@ -408,10 +408,7 @@ export const hardDeleteCardMemberRelationship = async (
.delete() .delete()
.eq("cardId", args.cardId) .eq("cardId", args.cardId)
.eq("workspaceMemberId", args.memberId) .eq("workspaceMemberId", args.memberId)
.select() .select();
.order("cardId", { ascending: true })
.limit(1)
.single();
return { success: !error }; return { success: !error };
}; };