Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save captainhusaynpenguin/5bdb6fcb141628b6865619bcd1c827fd to your computer and use it in GitHub Desktop.
Save captainhusaynpenguin/5bdb6fcb141628b6865619bcd1c827fd to your computer and use it in GitHub Desktop.

Quick start

Tauri is shipped with state management function/feature by default.

Basic usage is quite simple: a variable of State type can be accessed on the tauri commands which you have defined; in other words, "with tauri commands, they'll magically inject state for you," so that once a variable is managed you can inject them directly as additional input when defining the command.

Example Implementation

In this example, our front-end passes a path variable to the bakcend via retrieve_scroll command [which is custom command we defined];

  1. Require respective modules:
use std::sync::Mutex;
use tauri::State;
  1. Declare a stract holding the variable you would like to share across your commands:
struct Note(Mutex<String>);
  1. Initialize it in the main() function by chaining manager() to tauri:
 tauri::Builder::default()
  .manage(Note(Default::default()))
  .invoke_handler(tauri::generate_handler![
    retrieve_scroll,
  ])
  .run(tauri::generate_context!())
  .expect("error while running tauri application");
  1. Access your variable by adding an additional input:
fn retrieve_scroll(path: &str, note: State<Note>) -> String{
  let mut nt = note.0.lock().unwrap();
  let mut base = PathBuf::from(path);
  *nt = base.display().to_string();
  1. Now if you add note: State<Note> to your inputs in other commands, you will get the value that is stored in memory refernced by the note instance in the backend, so, you don't need to pass the path value from the front-end anymore. That is, of course, if you have to change the value of the path.

Questions / Todos

  • what is the extend of "manager". I couldn't really find any docs on https://tauri.studio
  • why are we indexing 0 when unlocking the struct?

Because Note is a "tuple struct" (https://doc.rust-lang.org/rust-by-example/custom_types/structs.html) and the Mutex is the first item of the tuple; indexes generally start at 0 therefore we use note.0 to tell rust that we want the Mutex from the struct

By FabianLars

Disclaimer

This is note for personal reference, also encouragement for others [more experienced, skilled, educated] to delve into more detailed on managing states in a Rust application.

The aspiration is to have a booklet which teaches best practices in state management specifically for applications:

  • desgined with a front-end back-end architecture paradigm
  • feature / scalable to function entirely offline / online / [auto] sync (read it "hybrid")
  • ...

Refrences

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment