Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Maintain State In Tauri Apps

This is how I'm maintaining state in the Rust portion of my Tauri apps. The method uses [TODO: Code shorthand span ] and [TODO: Code shorthand span ] to hold on to the values.

The example provides an input field and "Set State" button that stores a String. The "Get State" button retreives the String and outputs it on the page.

File: src/index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <script>
    const {invoke} = window.__TAURI__.tauri;
    async function setState() {
      await invoke("set_state", {name: inputEl.value});
    }
    async function getState() {
      outputEl.innerHTML = await invoke("get_state");
    }
    window.addEventListener("DOMContentLoaded", () => {
      setStateButton.addEventListener('click', setState)
      getStateButton.addEventListener('click', getState)
    });
  </script>
</head>

<body>
  <div>
    <button id="setStateButton">Set State</button>
    <input id="inputEl" />
  </div>
  <div>
    <button id="getStateButton">Get State</button>
    <span id="outputEl"></span>
  </div>
</body>

</html>

File: src-tauri/src/main.rs

rust
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use std::sync::Mutex;
use tauri::State;

struct Storage {
    example_value: Mutex<Option<String>>,
}

#[tauri::command]
fn set_state(name: &str, store: State<Storage>) {
    let mut v = store.example_value.lock().unwrap();
    *v = Some(name.to_string());
}

#[tauri::command]
fn get_state(store: State<Storage>) -> String {
    let v = store.example_value.lock().unwrap();
    format!("{}", v.as_ref().unwrap())
}

fn main() {
    tauri::Builder::default()
        .manage(Storage {
            example_value: Some("no state yet".to_string()).into(),
        })
        .invoke_handler(tauri::generate_handler![set_state, get_state])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

Footnotes And References