AI에게 추천받기 버튼을 눌러 투두리스트를 추천 받아, 새로운 투두리스트가 생길 때 저장하기와 초기화하기 버튼이 뜨지 않음
return NextResponse.json({
message: [
{ ...userMessage },
{ ...aiMessage },
showSaveButton ? { ...saveButtonMessage, showSaveButton } : null
].filter(Boolean),
todoListCompleted,
newTodoItems: hasNewTodoItems ? todoItems : [],
currentTodoList: updatedTodoList,
});
const sendMessageMutation = useMutation<ServerResponse, Error, string, MutationContext>({
mutationFn: async (newMessage: string) => {
const response = await fetch(`/api/chat/${aiType}/${sessionId}`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ message: newMessage, todoMode, currentTodoList })
});
// 수정할 때 스펠링이 잘못되면 오류를 던지는게 아니라 toast.warn 띄워주기
if (!response.ok) {
throw new Error("Network response was not ok");
}
const data = await response.json();
setIsNewConversation(true);
console.log("sendMessageMutation data", data);
return data;
},
onMutate: async (newMessage): Promise<MutationContext> => {
await queryClient.cancelQueries({ queryKey: [queryKeys.chat, aiType, sessionId] });
const previousMessages = queryClient.getQueryData<Message[]>([queryKeys.chat, aiType, sessionId]);
const userMessage: MessageWithButton = {
role: "user" as const,
content: newMessage,
created_at: new Date().toISOString(),
showSaveButton: false
};
queryClient.setQueryData<Message[]>([queryKeys.chat, aiType, sessionId], (oldData) => [
...(oldData || []),
userMessage
]);
return { previousMessages };
},
onSuccess: (data, variables, context) => {
console.log("sendMessageMutation data", data);
queryClient.setQueryData<MessageWithButton[]>([queryKeys.chat, aiType, sessionId], (oldData = []) => {
const withoutOptimisticUpdate = oldData.slice(0, -1);
return [...withoutOptimisticUpdate, ...data.message];
});
if (data.currentTodoList) {
setCurrentTodoList(data.currentTodoList);
}
if (data.newTodoItems && data.newTodoItems.length > 0) {
setCurrentTodoList((prevList) => {
const updatedList = [...new Set([...prevList, ...data.newTodoItems])];
return updatedList;
});
}
setTodoMode("createTodo");
setIsNewConversation(true);
},
onError: (error, newMessage, context) => {
console.error("Error sending message", error);
if (context?.previousMessages) {
queryClient.setQueryData([queryKeys.chat, aiType, sessionId], context?.previousMessages);
}
}
});
기존에 todoMode에 따라서 조건부로 나눠주어 todoMode === "recommend"인 경우가 있었지만, 해당 조건이 만족하는 경우가 없다는 것을 파악하여, todoMode === "createTodo"인 경우의 수에 todoRequestType === "recommend"인 경우를 함께 넣어주어 추천받아서 투두가 생기는 경우에도 기존의 저장하기와 초기화하기 버튼이 뜨는 것을 수정
if (todoMode === "createTodo") {
if (todoRequestType === "create") {
console.log("create => ", todoRequestType);
updatedTodoList = [...new Set([...updatedTodoList, ...todoItems])];
showSaveButton = todoItems.length > 0; // 항목이 추가된 경우에만 save 버튼 표시
} else if (todoRequestType === "add") {
console.log("add => ", todoRequestType);
updatedTodoList = [...new Set([...updatedTodoList, ...todoItems])];
showSaveButton = todoItems.length > 0;
} else if (todoRequestType === "delete") {
console.log("delete");
if (todoItems.length > 0) {
updatedTodoList = todoItems;
} else {
console.log("No items to delete found");
}
console.log("delete updatedTodoList => ", updatedTodoList);
showSaveButton = todoItems.length > 0;
} else if (todoRequestType === "update") {
console.log("update");
showSaveButton = todoItems.length > 0;
} else if (todoRequestType === "recommend") {
console.log("recommend");
console.log("recommendTodo", todoItems);
updatedTodoList = todoItems;
showSaveButton = todoItems.length > 0;
}
} else if (todoMode === "resetTodo") {
console.log("reset");
todoItems = [];
updatedTodoList = [];
showSaveButton = false;
} else {
console.log("Unknown todoMode");
}