From 1b5ed25fda92435bbf70d8b926ffbc0f80fc70e0 Mon Sep 17 00:00:00 2001 From: Jashwanth-rit <158207370+Jashwanth-rit@users.noreply.github.com> Date: Sat, 21 Sep 2024 18:55:49 +0530 Subject: [PATCH] fix:29 fix:30 --- client/src/components/ItemDisplay.scss | 3 +- client/src/components/TodoListCard.jsx | 40 +++++++++++++++++--------- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/client/src/components/ItemDisplay.scss b/client/src/components/ItemDisplay.scss index 3c009b2..91b2683 100644 --- a/client/src/components/ItemDisplay.scss +++ b/client/src/components/ItemDisplay.scss @@ -12,7 +12,8 @@ } &.completed { - text-decoration: line-through; + color: #aaa; + opacity: 0.5; } } diff --git a/client/src/components/TodoListCard.jsx b/client/src/components/TodoListCard.jsx index 0092344..cf457d0 100644 --- a/client/src/components/TodoListCard.jsx +++ b/client/src/components/TodoListCard.jsx @@ -5,37 +5,49 @@ import { ItemDisplay } from './ItemDisplay'; export function TodoListCard() { const [items, setItems] = useState(null); + const sortItems = (items) => { + // Sort items: incomplete first, completed last, and newly added at the top + return items.sort((a, b) => { + if (a.completed === b.completed) { + return b.id.localeCompare(a.id); // Compare by ID to show newly added items first + } + return a.completed - b.completed; // Incomplete items first + }); + }; + useEffect(() => { fetch('/api/items') .then((r) => r.json()) - .then(setItems); + .then((data) => setItems(sortItems(data))); // Apply sorting after fetching items }, []); const onNewItem = useCallback( (newItem) => { - setItems([...items, newItem]); + setItems((prevItems) => sortItems([...prevItems, newItem])); }, - [items], + [], ); const onItemUpdate = useCallback( - (item) => { - const index = items.findIndex((i) => i.id === item.id); - setItems([ - ...items.slice(0, index), - item, - ...items.slice(index + 1), - ]); + (updatedItem) => { + setItems((prevItems) => { + const updatedItems = prevItems.map((item) => + item.id === updatedItem.id ? updatedItem : item + ); + return sortItems(updatedItems); + }); }, - [items], + [], ); const onItemRemoval = useCallback( (item) => { - const index = items.findIndex((i) => i.id === item.id); - setItems([...items.slice(0, index), ...items.slice(index + 1)]); + setItems((prevItems) => { + const updatedItems = prevItems.filter((i) => i.id !== item.id); + return sortItems(updatedItems); + }); }, - [items], + [], ); if (items === null) return 'Loading...';