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({
items,
children,
disabled,
}: {
items: { label: string; action: () => void; icon?: React.ReactNode }[];
children: React.ReactNode;
disabled?: boolean;
}) {
return (
<Menu as="div" className="relative inline-block text-left">
<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}
</Menu.Button>
</div>

View File

@@ -1,13 +1,11 @@
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 { ModalProvider } from "~/providers/modal";
import { BoardProvider } from "~/providers/board";
import { PopupProvider } from "~/providers/popup";
import { ThemeProvider } from "~/providers/theme";
import { api } from "~/utils/api";
const jakarta = Plus_Jakarta_Sans({
@@ -36,9 +34,7 @@ const MyApp: AppType = ({ Component, pageProps }) => {
<ThemeProvider>
<ModalProvider>
<PopupProvider>
<BoardProvider>
<Component {...pageProps} />
</BoardProvider>
<Component {...pageProps} />
</PopupProvider>
</ModalProvider>
</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 { useModal } from "~/providers/modal";
export default function BoardDropdown() {
export default function BoardDropdown({ isLoading }: { isLoading: boolean }) {
const { openModal } = useModal();
return (
<Dropdown
disabled={isLoading}
items={[
{
label: "Edit board URL",

View File

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

View File

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

View File

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

View File

@@ -86,11 +86,11 @@ export function NewCardForm({
listId: 2,
description: "",
labels: oldBoard.labels.filter((label) =>
labelPublicIds.includes(label.publicId),
args.labelPublicIds.includes(label.publicId),
),
members:
oldBoard.workspace?.members.filter((member) =>
memberPublicIds.includes(member.publicId),
args.memberPublicIds.includes(member.publicId),
) ?? [],
_filteredLabels: labelPublicIds.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 type { NewListInput } from "@kan/api/types";
import { generateUID } from "@kan/shared/utils";
import Button from "~/components/Button";
import Input from "~/components/Input";
import Toggle from "~/components/Toggle";
import { useBoard } from "~/providers/board";
import { useModal } from "~/providers/modal";
import { usePopup } from "~/providers/popup";
import { api } from "~/utils/api";
@@ -16,11 +16,24 @@ type NewListFormInput = NewListInput & {
isCreateAnotherEnabled: boolean;
};
export function NewListForm({ boardPublicId }: { boardPublicId: string }) {
const { refetchBoard, addList } = useBoard();
interface QueryParams {
boardPublicId: string;
members: string[];
labels: string[];
}
export function NewListForm({
boardPublicId,
queryParams,
}: {
boardPublicId: string;
queryParams: QueryParams;
}) {
const { closeModal } = useModal();
const { showPopup } = usePopup();
const utils = api.useUtils();
const { register, handleSubmit, reset, setValue, watch } =
useForm<NewListFormInput>({
defaultValues: {
@@ -33,18 +46,41 @@ export function NewListForm({ boardPublicId }: { boardPublicId: string }) {
const isCreateAnotherEnabled = watch("isCreateAnotherEnabled");
const createList = api.list.create.useMutation({
onSuccess: async () => {
await refetchBoard();
onMutate: async (args) => {
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 () => {
closeModal();
await refetchBoard();
onError: (_error, _newList, context) => {
utils.board.byId.setData(queryParams, context?.previousState);
showPopup({
header: "Unable to create list",
message: "Please try again later, or contact customer support.",
icon: "error",
});
},
onSettled: async () => {
await utils.board.byId.invalidate(queryParams);
},
});
useEffect(() => {
@@ -54,7 +90,6 @@ export function NewListForm({ boardPublicId }: { boardPublicId: string }) {
}, []);
const onSubmit = (data: NewListInput) => {
addList(data);
const isCreateAnotherEnabled = watch("isCreateAnotherEnabled");
if (!isCreateAnotherEnabled) closeModal();
reset({

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
import { useRouter } from "next/navigation";
import { useBoard } from "~/providers/board";
import Button from "~/components/Button";
import { useModal } from "~/providers/modal";
import { usePopup } from "~/providers/popup";
import { api } from "~/utils/api";
@@ -15,26 +15,53 @@ export function DeleteCardConfirmation({
boardPublicId,
}: DeleteCardConfirmationProps) {
const { closeModal } = useModal();
const utils = api.useUtils();
const router = useRouter();
const { removeCard, refetchBoard } = useBoard();
const { showPopup } = usePopup();
const queryParams = {
boardPublicId,
};
const deleteCardMutation = api.card.delete.useMutation({
onSuccess: () => refetchBoard(),
onError: () =>
onMutate: async (args) => {
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({
header: "Error deleting card",
header: "Unable to delete card",
message: "Please try again later, or contact customer support.",
icon: "error",
}),
});
},
onSuccess: () => {
router.push(`/boards/${boardPublicId}`);
},
onSettled: async () => {
closeModal();
await utils.board.byId.invalidate(queryParams);
},
});
const handleDeleteCard = () => {
removeCard({
cardPublicId,
});
closeModal();
router.push(`/boards/${boardPublicId}`);
deleteCardMutation.mutate({
cardPublicId,
});
@@ -57,12 +84,12 @@ export function DeleteCardConfirmation({
>
Cancel
</button>
<button
<Button
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
</button>
</Button>
</div>
</div>
);