feat: optimisic updates

This commit is contained in:
Henry
2023-11-14 21:08:13 +00:00
parent decfe2dd98
commit 9660a60276
8 changed files with 181 additions and 33 deletions

View File

@@ -3,7 +3,7 @@
import { Fragment } from "react";
import { Dialog, Transition } from "@headlessui/react";
import { useModal } from "~/app/providers";
import { useModal } from "~/app/providers/modal";
interface Props {
children: React.ReactNode;

View File

@@ -10,6 +10,7 @@ import {
} from "react-beautiful-dnd";
import { api } from "~/trpc/react";
import { useBoard } from "~/app/providers/board";
interface List {
publicId: string;
@@ -24,35 +25,20 @@ interface Card {
export default function BoardPage() {
const params = useParams();
const utils = api.useUtils();
const { boardData, setBoardData, updateCard, updateList } = useBoard();
const boardId = params?.id?.length && params.id[0];
if (!boardId) return <></>;
const { data } = api.board.byId.useQuery({ id: boardId });
const refetchBoard = () => utils.board.byId.refetch({ id: boardId });
const updateCard = api.card.update.useMutation({
onSuccess: async () => {
try {
await refetchBoard();
} catch (e) {
console.log(e);
}
api.board.byId.useQuery(
{ id: boardId },
{
onSuccess: (data) => {
if (data) setBoardData(data);
},
},
});
const updateList = api.list.update.useMutation({
onSuccess: async () => {
try {
await refetchBoard();
} catch (e) {
console.log(e);
}
},
});
);
const onDragEnd = ({
source,
@@ -65,7 +51,16 @@ export default function BoardPage() {
}
if (type === "LIST") {
updateList.mutate({
const updatedLists = Array.from(boardData.lists);
const removedList = updatedLists.splice(source.index, 1)[0];
if (removedList) {
updatedLists.splice(destination.index, 0, removedList);
setBoardData({ ...boardData, lists: updatedLists });
}
updateList({
boardId,
listId: draggableId,
currentIndex: source.index,
@@ -74,7 +69,22 @@ export default function BoardPage() {
}
if (type === "CARD") {
updateCard.mutate({
const updatedLists = Array.from(boardData.lists);
const sourceList = updatedLists.find(
(list) => list.publicId === source.droppableId,
);
const destinationList = updatedLists.find(
(list) => list.publicId === destination.droppableId,
);
const removedCard = sourceList?.cards.splice(source.index, 1)[0];
if (sourceList && destinationList && removedCard) {
destinationList.cards.splice(destination.index, 0, removedCard);
setBoardData({ ...boardData, lists: updatedLists });
}
updateCard({
cardId: draggableId,
currentListId: source.droppableId,
newListId: destination.droppableId,
@@ -88,7 +98,7 @@ export default function BoardPage() {
<div>
<div className="mb-8 flex w-full justify-between">
<h1 className="font-medium tracking-tight text-dark-1000 sm:text-[1.2rem]">
{data?.name}
{boardData?.name}
</h1>
<div>
<button
@@ -112,7 +122,7 @@ export default function BoardPage() {
ref={provided.innerRef}
{...provided.droppableProps}
>
{data?.lists.map((list: List, index) => (
{boardData?.lists?.map((list: List, index) => (
<Draggable
key={list.publicId}
draggableId={list.publicId}

View File

@@ -4,7 +4,7 @@ import { api } from "~/trpc/react";
import { HiXMark } from "react-icons/hi2";
import { useModal } from "~/app/providers";
import { useModal } from "~/app/providers/modal";
import { Formik, Form, Field } from "formik";

View File

@@ -3,7 +3,7 @@
import { HiOutlinePlusSmall } from "react-icons/hi2";
import { Boards } from "./boards";
import { useModal } from "~/app/providers";
import { useModal } from "~/app/providers/modal";
import Modal from "~/app/_components/modal";
import { NewBoardForm } from "~/app/boards/create";

View File

@@ -4,7 +4,8 @@ import { Plus_Jakarta_Sans } from "next/font/google";
import { headers } from "next/headers";
import { TRPCReactProvider } from "~/trpc/react";
import { ModalProvider } from "~/app/providers";
import { ModalProvider } from "~/app/providers/modal";
import { BoardProvider } from "~/app/providers/board";
const jakarta = Plus_Jakarta_Sans({
subsets: ["latin"],
@@ -26,7 +27,9 @@ export default function RootLayout({
<html lang="en">
<body className={`font-sans ${jakarta.className}}`}>
<TRPCReactProvider headers={headers()}>
<ModalProvider>{children}</ModalProvider>
<ModalProvider>
<BoardProvider>{children}</BoardProvider>
</ModalProvider>
</TRPCReactProvider>
</body>
</html>

135
src/app/providers/board.tsx Normal file
View File

@@ -0,0 +1,135 @@
"use client";
import React, {
createContext,
useContext,
useState,
type ReactNode,
} from "react";
import { api } from "~/trpc/react";
interface BoardContextProps {
boardData: BoardData;
setBoardData: React.Dispatch<React.SetStateAction<BoardData>>;
updateList: (params: UpdateListParams) => void;
updateCard: (params: UpdateCardParams) => void;
}
interface BoardData {
name: string;
publicId: string;
lists: List[];
}
interface List {
publicId: string;
name: string;
boardId: number;
index: number;
cards: Card[];
}
interface Card {
publicId: string;
title: string;
}
interface UpdateListParams {
boardId: string;
listId: string;
currentIndex: number;
newIndex: number;
}
interface UpdateCardParams {
cardId: string;
currentListId: string;
newListId: string;
currentIndex: number;
newIndex: number;
}
const initialBoardData: BoardData = {
name: "",
publicId: "",
lists: [],
};
const BoardContext = createContext<BoardContextProps | undefined>(undefined);
export const BoardProvider: React.FC<{ children: ReactNode }> = ({
children,
}) => {
const utils = api.useUtils();
const [boardData, setBoardData] = useState<BoardData>(initialBoardData);
const refetchBoard = () =>
utils.board.byId.refetch({ id: boardData.publicId });
const updateCardMutation = api.card.update.useMutation({
onSuccess: async () => {
try {
await refetchBoard();
} catch (e) {
console.log(e);
}
},
});
const updateListMutation = api.list.update.useMutation({
onSuccess: async () => {
try {
await refetchBoard();
} catch (e) {
console.log(e);
}
},
});
const updateList = ({
boardId,
listId,
currentIndex,
newIndex,
}: UpdateListParams) => {
updateListMutation.mutate({
boardId,
listId,
currentIndex,
newIndex,
});
};
const updateCard = ({
cardId,
currentListId,
newListId,
currentIndex,
newIndex,
}: UpdateCardParams) => {
updateCardMutation.mutate({
cardId,
currentListId,
newListId,
currentIndex,
newIndex,
});
};
return (
<BoardContext.Provider
value={{ boardData, setBoardData, updateList, updateCard }}
>
{children}
</BoardContext.Provider>
);
};
export const useBoard = (): BoardContextProps => {
const context = useContext(BoardContext);
if (!context) {
throw new Error("useBoard must be used within a BoardProvider");
}
return context;
};

View File

@@ -25,7 +25,7 @@ export const boards = mySqlTable(
{
id: bigint("id", { mode: "number" }).primaryKey().autoincrement(),
publicId: varchar("publicId", { length: 12 }).notNull().unique(),
name: varchar("name", { length: 255 }),
name: varchar("name", { length: 255 }).notNull(),
createdBy: varchar("createdBy", { length: 255 }).notNull(),
createdAt: timestamp("createdAt")
.default(sql`CURRENT_TIMESTAMP`)