Maintain State In Tauri Apps

This is how I'm maintaining state in the Rust portion of my Tauri apps. The method uses `tauri::State`` and `std::sync::Mutex`` 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

#![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");
}

References