現在來修改我們的新增和刪除功能
將handleTaskAdd更名為handleTodoAdd並修改:
const handleTodoAdd = async () => {
await invoke("new_todo", { title: todo.title, date: Date.now.toString() });
setTodo({...todo, title: ""});
}
測試
!!Bug:這裡有時候會出現App會一直重啟的問題,尋找後,發現可能是tauri會觀察你的目錄是否有變化並且會重啟。(Solve)解決方法是新增.taurignore
至./src
和./src-tauri
的目錄下,並在.taurignore
加入
*
!src/**/*
!src-tauri/**/*
接著,我們進行測試
將handleTaskDelete更名為handleTodoDelete並修改:
const handleTodoDelete = async (id: number) => {
await invoke("delete_todo", { id: id});
setTodo({...todo, title: ""});
}
並且修改UI
<button type="button" onClick={() => handleTodoDelete(todo.id)}>
Delete
</button>
<div className="container">
<h1>Welcome to Todo List</h1>
<div className="row">
<input
id="greet-input"
onChange={(e) => handleTitleChange(e)}
placeholder="Enter a task..."
value={todo.title}
/>
<button type="button" onClick={() => handleTodoAdd()}>
Add
</button>
</div>
<hr />
{todos.map((todo, index) => {
return (
<div className="row" key={index}>
<div style={itemStyle}>{todo.title}</div>
<button type="button" onClick={() => handleTodoDelete(todo.id)}>
Delete
</button>
</div>
);
})}
</div>
F5重新整理後進行測試
backend
sqlite
index.tsx
import { useEffect, useState } from "react";
import { invoke } from '@tauri-apps/api/tauri';
const itemStyle = {
padding: '8px',
};
interface Todo {
id: number,
title: string,
date: string,
done: boolean
}
function App() {
const [todos, setTodos] = useState<Todo[]>([]);
const [todo, setTodo] = useState<Todo>({id: -1, title: "", date: "None", done: false});
useEffect(()=> {
fetchAllTodo();
}, [todos]);
const fetchAllTodo = async () => {
setTodos(await invoke("get_todos"));
}
const handleTitleChange = (e: React.FormEvent<HTMLInputElement>) => {
let value = e.currentTarget.value;
setTodo({...todo, title: value});
}
const handleTodoAdd = async () => {
await invoke("new_todo", { title: todo.title, date: Date.now.toString() });
setTodo({...todo, title: ""});
}
const handleTodoDelete = async (id: number) => {
console.log(id);
await invoke("delete_todo", { id: id});
setTodo({...todo, title: ""});
}
return (
<div className="container">
<h1>Welcome to Todo List</h1>
<div className="row">
<input
id="greet-input"
onChange={(e) => handleTitleChange(e)}
placeholder="Enter a task..."
value={todo.title}
/>
<button type="button" onClick={() => handleTodoAdd()}>
Add
</button>
</div>
<hr />
{todos.map((todo, index) => {
return (
<div className="row" key={index}>
<div style={itemStyle}>{todo.title}</div>
<button type="button" onClick={() => handleTodoDelete(todo.id)}>
Delete
</button>
</div>
);
})}
</div>
);
}
export default App;
今天我們完成了新增和刪除的功能,我們明天見