rusttauri

Mutable app state in Tauri accessible from tauri::command


I am working on a proof-of-concept migrating a Capacitor app to Tauri. I would like to be able to access mutable app state within #[tauri::command] functions, but am finding it challenging to do that without resorting to global mutable variables.

Tauri's documentation on state management suggests passing state to the #[tauri::command] function like this:

#[tauri::command]
fn increase_counter(state: State<'_, Mutex<AppState>>) -> u32 {
  let mut state = state.lock().unwrap();
  state.counter += 1;
  state.counter
}

I am reading the v2.0 RC documentation, but this appears to be the same or similar in v1.

The problem with this approach is that I would then need to provide the state in my calls from my JavaScript UI, correct? I would prefer the state be maintained entirely in my Rust code and not concern myself with passing it back and forth across the JavaScript barrier.

Is there an idiomatic way to do this in Tauri that I am missing, or do I need to use lazy_static or some other workaround?


Solution

  • The problem with this approach is that I would then need to provide the state in my calls from my JavaScript UI, correct?

    Incorrect, the State command argument accesses values that were provided to .manage(). These arguments are not provided by a JavaScript parameter and don't cross the Rust-JavaScript barrier. This is the same behavior in both 1.0 and 2.0.

    What you have is idiomatic and already does what you want (given that you provide an initial Mutex<AppState> to your App via manage). The documentation has examples for complete usage.