首先,先修復date問題,回到todo\src\pages\index.tsx
將handleTodoAdd
const handleTodoAdd = async () => {
await invoke("new_todo", { title: todo.title, date: Date.now.toString() });
setTodo({...todo, title: ""});
}
修改成
const handleTodoAdd = async () => {
let date = Date.now().toString();
await invoke("new_todo", { title: todo.title, date: date });
setTodo({...todo, title: ""});
}
今天我們來實現匯入csv
首先,建立handleImportFile
// Import
const handleImportFile = async () => {
const csv = await readTextFile('todos.csv', { dir: BaseDirectory.Download });
var lines=csv.split("\n");
let result = [];
var headers=lines[0].split(",");
for(var i=1;i<lines.length;i++){
var obj = {};
var currentline=lines[i].split(",");
for(var j=0;j<headers.length;j++){
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
result.forEach(async (element: Todo) => {
await invoke("new_todo", { title: element.title, date: element.date });
});
await message('Import all todos!!', 'Import done!!');
}
將button加入UI
<div>
<button type="button" onClick={() => handleImportFile()}>
Import
</button>
</div>
測試,首先先刪除先前的Todo並創建新Todo
匯出csv
刪除所有的Todo,並點選匯入
此時,我們已將檔案匯入,我們看一下Database已經將檔案給匯入
我們今天簡單的實現匯入檔案,接下來幾天是對我們的app來進行重構並優化,我們明天見。