11"use client" ;
22
3- import DoneEmpty from "@/features/todo/components/DoneEmpty" ;
3+ import { startTransition , useOptimistic , useRef } from "react" ;
4+
5+ import DoneEmpty from "@/app/_components/Empty/DoneEmpty" ;
6+ import TodoEmpty from "@/app/_components/Empty/TodoEmpty" ;
47import TodoContent from "@/features/todo/components/TodoContent" ;
5- import TodoEmpty from "@/features/todo/components/TodoEmpty" ;
68import { updateTodoItem } from "@/features/todo/services/todoApi" ;
79import { TodoItemType } from "@/types/todoTypes" ;
8- import { startTransition , useEffect , useOptimistic , useState } from "react" ;
910
1011interface Props {
1112 data : TodoItemType [ ] ;
1213 onUpdate ?: ( id : number ) => void ;
1314}
1415
1516const TodoListArea = ( { data } : Props ) => {
16- const [ todoAll , setTodoAll ] = useState ( data ) ;
17+ const initialDataRef = useRef < TodoItemType [ ] > ( data ) ;
1718 const [ optimisticState , toggleOptimisticState ] = useOptimistic <
1819 TodoItemType [ ] ,
1920 number
20- > ( todoAll , ( currentState , id ) => {
21+ > ( initialDataRef . current , ( currentState , id ) => {
2122 return currentState . map ( ( todo ) =>
2223 todo . id === id ? { ...todo , isCompleted : ! todo . isCompleted } : todo
2324 ) ;
@@ -28,30 +29,23 @@ const TodoListArea = ({ data }: Props) => {
2829 // 낙관적 업데이트
2930 toggleOptimisticState ( id ) ;
3031
31- const targetCheck = todoAll . find ( ( todo ) => todo . id === id ) ?. isCompleted ;
32+ const targetCheck = optimisticState . find (
33+ ( todo ) => todo . id === id
34+ ) ?. isCompleted ;
3235 const updateData = { isCompleted : ! targetCheck } ;
3336
34- const prevTodoAll = todoAll ;
35-
3637 try {
37- setTodoAll ( ( prevTodoAll ) =>
38- prevTodoAll . map ( ( todo ) =>
39- todo . id === id ? { ...todo , isCompleted : ! todo . isCompleted } : todo
40- )
41- ) ;
4238 await updateTodoItem ( id , updateData ) ;
39+ const updateTodo = initialDataRef . current . map ( ( todo ) =>
40+ todo . id === id ? { ...todo , isCompleted : ! todo . isCompleted } : todo
41+ ) ;
42+ initialDataRef . current = updateTodo ;
4343 } catch ( error ) {
4444 console . error ( error ) ;
45-
46- setTodoAll ( prevTodoAll ) ;
4745 }
4846 } ) ;
4947 } ;
5048
51- useEffect ( ( ) => {
52- setTodoAll ( data ) ;
53- } , [ data ] ) ;
54-
5549 const todoData = optimisticState . filter ( ( item ) => ! item . isCompleted ) ;
5650 const doneData = optimisticState . filter ( ( item ) => item . isCompleted ) ;
5751
0 commit comments