Files
archived-tauri-docs/src/content/docs/plugin/store.mdx
2024-09-29 19:09:56 -06:00

162 lines
5.1 KiB
Plaintext

---
title: Store
description: Persistent key value storage.
plugin: store
---
import PluginLinks from '@components/PluginLinks.astro';
import Compatibility from '@components/plugins/Compatibility.astro';
import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';
import CommandTabs from '@components/CommandTabs.astro';
import PluginPermissions from '@components/PluginPermissions.astro';
<PluginLinks plugin={frontmatter.plugin} />
This plugin provides a persistent key-value store. This is one of many options to handle state in your application. See the [state management overview](/develop/state-management/) for more information on additional options.
This store will allow you to persist state to a file which can be saved and loaded on demand including between app restarts. Note that this process is asynchronous which will require handling it within your code. It can be used both in the webview or within Rust.
## Supported Platforms
<Compatibility plugin={frontmatter.plugin} />
## Setup
Install the store plugin to get started.
<Tabs>
<TabItem label="Automatic">
Use your project's package manager to add the dependency:
<CommandTabs npm="npm run tauri add store"
yarn="yarn run tauri add store"
pnpm="pnpm tauri add store"
bun="bun tauri add store"
cargo="cargo tauri add store" />
</TabItem>
<TabItem label="Manual">
<Steps>
1. Run the following command in the `src-tauri` folder to add the plugin to the project's dependencies in `Cargo.toml`:
```sh frame=none
cargo add tauri-plugin-store
```
2. Modify `lib.rs` to initialize the plugin:
```rust title="src-tauri/src/lib.rs" ins={4}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_store::Builder::new().build())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
```
3. Install the JavaScript Guest bindings using your preferred JavaScript package manager:
<CommandTabs
npm = "npm install @tauri-apps/plugin-store"
yarn = "yarn add @tauri-apps/plugin-store"
pnpm = "pnpm add @tauri-apps/plugin-store"
bun = "bun add @tauri-apps/plugin-store"
/>
</Steps>
</TabItem>
</Tabs>
## Usage
<Tabs>
<TabItem label="JavaScript">
```javascript
import { Store } from '@tauri-apps/plugin-store';
// when using `"withGlobalTauri": true`, you may use
// const { Store } = window.__TAURI_PLUGIN_STORE__;
// Store will be loaded automatically when used in JavaScript binding.
const store = new Store('store.bin');
// Set a value.
await store.set('some-key', { value: 5 });
// Get a value.
const val = await store.get('some-key');
console.log(val); // { value: 5 }
// You can manually save the store after making changes.
// Otherwise, it will save upon graceful exit as described above.
await store.save();
```
</TabItem>
<TabItem label="Rust">
```rust title="src-tauri/src/lib.rs"
use tauri::Wry;
use tauri_plugin_store::{with_store, StoreCollection};
use serde_json::json;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_store::Builder::default().build())
.setup(|app| {
let stores = app.handle().try_state::<StoreCollection<Wry>>().ok_or("Store not found")?;
let path = PathBuf::from("store.bin");
with_store(app.handle().clone(), stores, path, |store| {
// Note that values must be serde_json::Value instances,
// otherwise, they will not be compatible with the JavaScript bindings.
store.insert("some-key".to_string(), json!({ "value": 5 }))?;
// Get a value from the store.
let value = store.get("some-key").expect("Failed to get value from store");
println!("{}", value); // {"value":5}
// You can manually save the store after making changes.
// Otherwise, it will save upon graceful exit as described above.
store.save()?;
Ok(())
});
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
```
</TabItem>
</Tabs>
## Permissions
By default, all plugin commands are blocked and cannot be accessed. You must define a list of permissions in your `capabilities` configuration.
See the [Capabilities Overview](/security/capabilities/) for more information and the [step by step guide](/learn/security/using-plugin-permissions/) to use plugin permissions.
```json title="src-tauri/capabilities/main.json" ins={6-11}
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "main-capability",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"store:allow-get",
"store:allow-set",
"store:allow-save",
"store:allow-load"
]
}
```
<PluginPermissions plugin={frontmatter.plugin} />