Persisting state
All your stores are automatically persisted to disk upon a graceful exit, but you can also manually save them if needed:
typescript
import { save, saveAll } from '@tauri-store/zustand';
// Save a single store.
await save('my-store');
// Save some stores.
await save('store-1', 'store-2', 'store-3');
// Save all stores.
await saveAll();
rust
use tauri_plugin_zustand::ManagerExt;
// Here, "manager" represents any type that implements the "Manager" trait provided by Tauri.
// This includes "AppHandle", "Window", and "WebviewWindow".
// See: https://docs.rs/tauri/latest/tauri/trait.Manager.html
// Save a single store.
manager.zustand().save("my-store");
// Save some stores.
manager.zustand().save_some(&["store-1", "store-2"]);
// Save all stores.
manager.zustand().save_all();
Save on change
If there's a need to save a store whenever its state changes, you can enable the saveOnChange
option when defining the store.
typescript
import { create } from 'zustand';
import { createTauriStore } from '@tauri-store/zustand';
const useCounterStore = create<{ counter: number }>((set) => ({
counter: 0,
}));
const tauriHandler = createTauriStore('counter', useCounterStore, {
saveOnChange: true,
// You can also debounce or throttle when saving.
// This is optional. The default behavior is to save immediately.
saveStrategy: 'debounce',
saveInterval: 1000,
});
Autosave
You can also enable autosave
to periodically write the stores to disk.
rust
use std::time::Duration;
// Save every five minutes.
tauri_plugin_zustand::Builder::new()
.autosave(Duration::from_secs(300))
.build();
Custom directory
By default, the stores are saved in a directory called tauri-plugin-zustand
within your app's data directory. You can change this by setting the path
option during the plugin's initialization.
rust
tauri_plugin_zustand::Builder::new()
.path("/path/to/custom/directory")
.build();
The path can also be modified at runtime. In this case, all currently active stores will be moved to the new directory.
typescript
import { setStoreCollectionPath } from '@tauri-store/zustand';
await setStoreCollectionPath('/path/to/new/directory');
rust
use tauri_plugin_zustand::ManagerExt;
manager.zustand().set_path("/path/to/new/directory");
Denylist
If a store should be synchronized, but not saved to disk, you can add it to the denylist.
rust
tauri_plugin_zustand::Builder::new()
.save_denylist(&["store-1", "store-2"])
.build();