Just started out with tauri. Trying to create some sort of todo app. Also trying to make it internet connection independent so for database i use .txt file
For now i got this:
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use serde::{Deserialize, Serialize};
use std::fs;
fn main() {
let mut check_items = get_check_items();
change_check_item_state(&mut check_items, 2);
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![create_check_item, change_check_item_state, delete_check_item])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
#[derive(Serialize, Deserialize, Debug)]
struct CheckItem {
id: u128,
title: String,
is_completed: bool,
created_at: String,
}
fn get_check_items() -> Vec<CheckItem> {
let strings_container = fs::read_to_string("file.txt").unwrap();
let deserialized_check_items: Vec<CheckItem> =
serde_json::from_str(&strings_container).unwrap();
return deserialized_check_items;
}
#[tauri::command]
fn create_check_item(check_items: &mut Vec<CheckItem>) {
let check_items =
check_items.push(CheckItem {
id: 4,
title: "from tauri".to_string(),
is_completed: true,
created_at: "2024.06.10.07:12".to_string(),
});
let serialized_check_items = serde_json::to_string_pretty(&check_items).unwrap();
let _ = fs::write("file.txt", serialized_check_items);
}
#[tauri::command]
fn delete_check_item(check_items: &mut Vec<CheckItem>, id: u128) {
check_items.retain(|check_item| check_item.id != id);
let serialized_check_items = serde_json::to_string_pretty(&check_items).unwrap();
let _ = fs::write("file.txt", serialized_check_items);
}
#[tauri::command]
fn change_check_item_state(check_items: &mut Vec<CheckItem>, id: u128) {
let check_item = check_items
.iter_mut()
.find(|check_item| check_item.id == id)
.unwrap();
check_item.is_completed = !check_item.is_completed;
let serialized_check_items = serde_json::to_string_pretty(&check_items).unwrap();
let _ = fs::write("file.txt", serialized_check_items);
}
It does not compile because &Vec<> does not implement CommandArg<, tauri_runtime_wry::Wry>.
This problem solves easily by copying check_items variable, but i don't want to do like this, because for every command i will have to copy full vector.
So i came to the conclusion that I need to create global variable for txt database
Is there any better solution or mine is good? If it's good what should i use to make it work?
PS
I understood that i can't even pass my db through params into functions because this functions will be called in frontend. So my only ways are creating global variable or read file every time i call command from frontend i guess