Skip to content

Commit

Permalink
Move state change operations to parent component of generic-listing.tsx
Browse files Browse the repository at this point in the history
  • Loading branch information
aahnik committed Dec 4, 2024
1 parent 8a3ba92 commit 752b410
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
16 changes: 10 additions & 6 deletions app/[orgId]/books/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,16 @@ export default function BooksPage() {
}, []);

const handleDelete = async (book: Book) => {
// Here you would typically make an API call to delete the book
// For now, we'll just simulate an API call
console.log("Attempting to delete", book);
await new Promise((resolve) => setTimeout(resolve, 500));
// The actual state update will be handled by the GenericListing component
try {
// Simulate API call
await new Promise((resolve) => setTimeout(resolve, 500));

// Update the state after successful API call
setBooks((prevBooks) => prevBooks.filter((b) => b.id !== book.id));
return Promise.resolve();
} catch (error) {
return Promise.reject(error);
}
};

const handleSave = async (book: Book) => {
Expand All @@ -56,7 +61,6 @@ export default function BooksPage() {
<>
<GenericListing
data={books}
setData={setBooks}
columns={columns}
title="Books"
searchableFields={["name", "author"]}
Expand Down
13 changes: 8 additions & 5 deletions mint/generic-listing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ export interface ColumnDef<T> {

interface GenericListingProps<T> {
data: T[];
setData: (data: T[]) => void;
columns: ColumnDef<T>[];
title: string;
searchableFields: (keyof T)[];
Expand All @@ -48,7 +47,6 @@ interface GenericListingProps<T> {

export function GenericListing<T extends { id: number | string }>({
data,
setData,
columns,
title,
searchableFields,
Expand Down Expand Up @@ -119,20 +117,25 @@ export function GenericListing<T extends { id: number | string }>({
const handleDelete = async () => {
if (itemToDelete && onDelete) {
try {
// First close the modal
setIsDeleteModalOpen(false);
setItemToDelete(null);

// Then perform the delete operation
await onDelete(itemToDelete);
setData(data.filter((item) => item.id !== itemToDelete.id));

// Show success toast
setToast({
type: ToastType.SUCCESS,
message: `Item has been deleted successfully.`,
});
} catch (error) {
// Show error toast
setToast({
type: ToastType.FAILURE,
message: `Failed to delete item: ${error instanceof Error ? error.message : "Unknown error"}`,
});
}
setIsDeleteModalOpen(false);
setItemToDelete(null);
}
};

Expand Down

0 comments on commit 752b410

Please sign in to comment.