Accessing from Rust
When the ManagerExt
trait is in scope, you can access your stores from any type that implements the Manager
trait (e.g. AppHandle
, Window
, WebviewWindow
).
Note that all values are stored as serde_json::Value
, so you may need to convert them to the desired type when accessing from Rust. You can check the serde_json
documentation for more information.
A list of all available methods for the stores can be found here.
rust
use tauri_plugin_zustand::ManagerExt;
#[tauri::command]
fn get_counter(app: AppHandle) -> i32 {
let value = app
.zustand()
.get("store", "counter")
.unwrap();
serde_json::from_value(value).unwrap()
}
You can also use the try_get
method to get the value directly as the desired type.
rust
use tauri_plugin_zustand::ManagerExt;
#[tauri::command]
fn try_get_counter(app: AppHandle) -> i32 {
app
.zustand()
.try_get::<i32>("store", "counter")
.unwrap()
}
Watching for changes
The watch
method can be used to set up a closure that will be called whenever the state of the store changes.
rust
use tauri_plugin_zustand::ManagerExt;
#[tauri::command]
fn watch_store(app: AppHandle) {
app.zustand().watch("store", |app| {
let counter = app
.zustand()
.try_get::<i32>("store", "counter")?;
println!("counter: {counter}");
Ok(())
});
}