Trying to the Tauri GUI on Rust : 4. State management on the Rust side
This time, I will make a count program using Rust’s state management.
I’ve tried it so far. I thought that if Tauri behaved like a browser, it would be possible to create various PWA-like apps on the front end side. But I don’t want to put emphasis on the front side (js etc.), and I don’t have much PWA skills in the first place. 😭 So I decided to try state management on the Rust side.
It is a continuation from the previous.
State management
In Tauri, it was written that state management can be done with the manager
function of tauri::builder. It seems to use Rust’s Mutex for retention and updates as described in Mutability.
Let’s use this to create a count program with a value on the Rust side.
Alright, let’s do it!
As usual, we’ll modify the previous source code.
First, edit index.html and add a count increase / decrease button.
In addition, prepare a function that sends the increase / decrease value to Rust and rewrites the HTML with the return value.
<div>
<Button onclick=”counter(1)”> + </Button>
<span id=”counter”> (^o^) </span>
<Button onclick=”counter(-1)”> — </Button>
</div><script>
const counter = (countVal) => {
invoke(‘counter’, {countVal: countVal})
.then((resultVal) => {
document.getElementById(‘counter’)
.innerHTML = String(resultVal);
});
};
</script>
Next, edit Rust’s src-tauri/src/main.rs.
Prepare a structure to hold the count value in Mutex, and start state management with manage()
of tauri::Builder.
Create a new counter()
handler function and update the counter value under state management with the increase / decrease value from JS.
use std::sync::Mutex;
use tauri::State;struct Counter(Mutex<i32>);#[tauri::command]
fn counter(count_val: i32, counter: State<Counter>) -> i32 {
// Lock the counter(Mutex) to get the current value
let mut ct = counter.0.lock().unwrap();
// Change and return a new value
*ct += count_val;
*ct
// Mutex is automatically unlocked when you exit the block
}fn main() {
tauri::Builder::default()
.manage(Counter(Default::default()))
.invoke_handler(tauri::generate_handler![
call_rust, // multiple handlers, separate them with commas.
counter, // Add one.
])
:
Let’s run it.
Click the +/- button. I was able to confirm the increase / decrease of the count value ! 😀
As an experiment, reload WebView and click the button. It can be confirmed that the value is inherited and the state is managed on the Rust side.
Paste the entire source code here.
Thank you for reading!
If you like it, please follow me.🤩
Next time, I’ll try the native message box and open file dialog.
Originally published at https://jnsmith.blog.fc2.com.