<aside> 💡 These are important documentation details for Tauri that I’ve found scouring Discord, GitHub issues, and other sources outside of the official documentation.
</aside>
Details about using Tauri app state management
Official example repo: https://github.com/tauri-apps/tauri/blob/dev/examples/state/main.rs
State structs that need to be updated must have interior mutability via Mutex
, RwLock
, and sometimes Arc
(although in my experience only a Mutex
is needed)
The best explanation here should really go into the official docs
To manage app state outside of a Tauri command
#[derive(Debug)]
pub struct ManagedState(pub Mutex<Option<AppState>>);
fn main() {
tauri::Builder::default()
.manage(ManagedState(Mutex::new(Some(AppState::new()))))
.setup(|app| {
*app.handle().state().0.lock().unwrap() = <my new state>;
Ok(())
})
}
From the Discord chat linked above:
Is it possible to modify state using the AppHandle.state() method? Yes. I think what's the problem here is that you don't tell the state function which State you're talking about.
// passed to app::manage
pub struct ManagedState(pub Mutex<Option<AppState>>);
let state: State<ManagedState<...>> = handle.state();
// or
let state = handle.state::<ManagedState<...>>();
When using threads, you must wrap state structs in an Arc
Pass the AppHandle
singleton instance to functions to access the state globally and in tauri::Builder::setup
Emit in commands: you can inject a Window or AppHandle into the command and use that to emit events
To access state in tauri::Builder::setup
:
Import the Manager trait
use tauri::Manager;
Useapp.state::<typeOfYourState>()
to receive previously stored state (with setup being the earliest entry point you may want to consider using app.manage() to store your state instead of the manage function of the builder.)
main.rs
so that it attaches to a console// main.rs
// #![cfg_attr(
// all(not(debug_assertions), target_os = "windows"),
// windows_subsystem = "windows"
// )]
For quickly transferring large chunks of data, use register_uri_scheme_protocol
(https://docs.rs/tauri/latest/tauri/struct.Builder.html#method.register_uri_scheme_protocol)
Example: https://github.com/tauri-apps/tauri/blob/dev/examples/streaming/main.rs