Improve toast notifications and reduce delay for row operations

This commit is contained in:
skidoodle 2024-12-30 13:54:34 +01:00
parent 95380493cb
commit dd3f79b81d
Signed by: albert
GPG key ID: A06E3070D7D55BF2
2 changed files with 34 additions and 29 deletions

View file

@ -55,13 +55,17 @@ export default function App() {
) => { ) => {
setLoading(true); setLoading(true);
try { try {
await new Promise((resolve) => setTimeout(resolve, 500)); await new Promise((resolve) => setTimeout(resolve, 250));
setData((prev) => setData((prev) =>
prev.map((item) => (item.id === originalRow.id ? updatedRow : item)), prev.map((item) => (item.id === originalRow.id ? updatedRow : item)),
); );
setRecentlyUpdatedRowId(updatedRow.id); setRecentlyUpdatedRowId(updatedRow.id);
setTimeout(() => setRecentlyUpdatedRowId(null), 1000); setTimeout(() => setRecentlyUpdatedRowId(null), 250);
toast.success("Row saved successfully");
} catch (err) {
toast.error("Error saving row. Please try again.");
console.error("Error saving row:", err);
} finally { } finally {
setLoading(false); setLoading(false);
} }
@ -72,7 +76,7 @@ export default function App() {
setLoading(true); setLoading(true);
try { try {
await new Promise((resolve) => setTimeout(resolve, 500)); await new Promise((resolve) => setTimeout(resolve, 250));
setData((prev) => [...prev, { ...newRow, id: `${Date.now()}` }]); setData((prev) => [...prev, { ...newRow, id: `${Date.now()}` }]);
setNewRow({ setNewRow({
@ -83,6 +87,10 @@ export default function App() {
note: "", note: "",
status: "Unpaid", status: "Unpaid",
}); });
toast.success("Row added successfully");
} catch (err) {
toast.error("Error adding row. Please try again.");
console.error("Error adding row:", err);
} finally { } finally {
setLoading(false); setLoading(false);
} }
@ -91,9 +99,13 @@ export default function App() {
const handleDeleteRow = async (id: string) => { const handleDeleteRow = async (id: string) => {
setLoading(true); setLoading(true);
try { try {
await new Promise((resolve) => setTimeout(resolve, 500)); await new Promise((resolve) => setTimeout(resolve, 250));
setData((prev) => prev.filter((item) => item.id !== id)); setData((prev) => prev.filter((item) => item.id !== id));
toast.success("Row deleted successfully");
} catch (err) {
toast.error("Error deleting row. Please try again.");
console.error("Error deleting row:", err);
} finally { } finally {
setLoading(false); setLoading(false);
} }
@ -102,7 +114,7 @@ export default function App() {
const toggleStatus = async (row: Budgetable) => { const toggleStatus = async (row: Budgetable) => {
setLoading(true); setLoading(true);
try { try {
await new Promise((resolve) => setTimeout(resolve, 500)); await new Promise((resolve) => setTimeout(resolve, 250));
setData((prev) => setData((prev) =>
prev.map((item) => prev.map((item) =>

View file

@ -1,6 +1,3 @@
"use client";
// Inspired by react-hot-toast library
import * as React from "react"; import * as React from "react";
import type { ToastActionElement, ToastProps } from "@/components/ui/toast"; import type { ToastActionElement, ToastProps } from "@/components/ui/toast";
@ -15,22 +12,20 @@ type ToasterToast = ToastProps & {
action?: ToastActionElement; action?: ToastActionElement;
}; };
const actionTypes = { type ActionType = {
ADD_TOAST: "ADD_TOAST", ADD_TOAST: "ADD_TOAST";
UPDATE_TOAST: "UPDATE_TOAST", UPDATE_TOAST: "UPDATE_TOAST";
DISMISS_TOAST: "DISMISS_TOAST", DISMISS_TOAST: "DISMISS_TOAST";
REMOVE_TOAST: "REMOVE_TOAST", REMOVE_TOAST: "REMOVE_TOAST";
} as const; };
let count = 0; let count = 0;
function genId() { function genId(): string {
count = (count + 1) % Number.MAX_SAFE_INTEGER; count = (count + 1) % Number.MAX_VALUE;
return count.toString(); return count.toString();
} }
type ActionType = typeof actionTypes;
type Action = type Action =
| { | {
type: ActionType["ADD_TOAST"]; type: ActionType["ADD_TOAST"];
@ -55,7 +50,7 @@ interface State {
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>(); const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>();
const addToRemoveQueue = (toastId: string) => { const addToRemoveQueue = (toastId: string): void => {
if (toastTimeouts.has(toastId)) { if (toastTimeouts.has(toastId)) {
return; return;
} }
@ -90,14 +85,12 @@ export const reducer = (state: State, action: Action): State => {
case "DISMISS_TOAST": { case "DISMISS_TOAST": {
const { toastId } = action; const { toastId } = action;
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) { if (toastId) {
addToRemoveQueue(toastId); addToRemoveQueue(toastId);
} else { } else {
state.toasts.forEach((toast) => { for (const t of state.toasts) {
addToRemoveQueue(toast.id); addToRemoveQueue(t.id);
}); }
} }
return { return {
@ -130,11 +123,11 @@ const listeners: Array<(state: State) => void> = [];
let memoryState: State = { toasts: [] }; let memoryState: State = { toasts: [] };
function dispatch(action: Action) { function dispatch(action: Action): void {
memoryState = reducer(memoryState, action); memoryState = reducer(memoryState, action);
listeners.forEach((listener) => { for (let i = 0; i < listeners.length; i++) {
listener(memoryState); listeners[i](memoryState);
}); }
} }
type Toast = Omit<ToasterToast, "id">; type Toast = Omit<ToasterToast, "id">;
@ -179,7 +172,7 @@ function useToast() {
listeners.splice(index, 1); listeners.splice(index, 1);
} }
}; };
}, [state]); }, []);
return { return {
...state, ...state,