今天將我們app中,裡面的Tauri Backend裡所創建的Todo功能與我們frontend的todo功能做繫結,讓我們的frontend能呼叫我們的command
首先,我們先創立Todo的類型
interface Todo {
id: number,
title: string,
date: string,
done: boolean
}
修改我們的state以及新增方法來取得我們的Todo,並且先將我們handleTaskAdd和handleTaskDelete功能註解掉
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 handleTaskAdd = async () => {
// setTodos([todo, ...todos]);
// setTodo('');
}
const handleTaskDelete = async (index) => {
// setTodos(todos.filter(e => e !== todos[index]));
// setTodo('');
}
修改ui裡的todo
<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(index)}>
Delete
</button>
</div>
);
})}
</div>
先測試一下,能看到顯示出我們的todo了
今天簡單的展示一下如何和Tauri前後端進行交互,明天開始加入新增和刪除功能