—
Tauri is shipped with state management function/feature by default.
Basic usage is quite simple: a variable of State type can be accessed on the tauri commands which you have defined; in other words, "with tauri commands, they'll magically inject state for you," so that once a variable is managed you can inject them directly as additional input when defining the command.
In this example, our front-end passes a path variable to the bakcend via retrieve_scroll
command [which is custom command we defined];
- Require respective modules:
use std::sync::Mutex;
use tauri::State;
- Declare a stract holding the variable you would like to share across your
commands
:
struct Note(Mutex<String>);
- Initialize it in the
main()
function by chainingmanager()
totauri
:
tauri::Builder::default()
.manage(Note(Default::default()))
.invoke_handler(tauri::generate_handler![
retrieve_scroll,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
- Access your variable by adding an additional input:
fn retrieve_scroll(path: &str, note: State<Note>) -> String{
let mut nt = note.0.lock().unwrap();
let mut base = PathBuf::from(path);
*nt = base.display().to_string();
- Now if you add
note: State<Note>
to your inputs in other commands, you will get the value that is stored in memory refernced by thenote
instance in the backend, so, you don't need to pass thepath
value from the front-end anymore. That is, of course, if you have to change the value of thepath
.
- what is the extend of "manager". I couldn't really find any docs on https://tauri.studio
- why are we indexing 0 when unlocking the struct?
Because Note is a "tuple struct" (https://doc.rust-lang.org/rust-by-example/custom_types/structs.html) and the Mutex is the first item of the tuple; indexes generally start at 0 therefore we use note.0 to tell rust that we want the Mutex from the struct
By FabianLars
This is note for personal reference, also encouragement for others [more experienced, skilled, educated] to delve into more detailed on managing states in a Rust application.
The aspiration is to have a booklet which teaches best practices in state management specifically for applications:
- desgined with a front-end back-end architecture paradigm
- feature / scalable to function entirely offline / online / [auto] sync (read it "hybrid")
- ...
- Discord answer by (DCEDDIA). https://discord.com/channels/616186924390023171/622768087183130673/975567244358742016
- Nakamura, Mar-M. "Trying to the Tauri GUI on Rust : 4. State management on the Rust side." https://medium.com/@marm.nakamura/trying-to-the-tauri-gui-on-rust-4-state-management-on-the-rust-side-8899bda08936.