How to run a slow task on button:click with Leptos?

309 Views Asked by At

I'm trying to PGP encrypt a string client side when user clicks on a button and this seems to be super slow. First when running in debug/dev mode with trunk serve --open it takes ages for the page to load with the code below. If I compile in production mode trunk build --release then it's faster but still loads much slower (~3-5s) compared to a JavaScript equivalent.

  1. How can I run a task that take takes a longer time to process in Leptos as code below freezes the UI for few seconds.
  2. Any idea how I can make it run faster? I would like it to be similar to the JavaScript version in regards to speed.
use base64::{engine::general_purpose, Engine as _};
use leptos::*;
use sequoia_openpgp::serialize::stream::{Encryptor, LiteralWriter, Message};
use std::io::Write;

#[component]
pub fn App() -> impl IntoView {
    let (data, set_data) = create_signal("".to_string());

    view! {
        <div>
            <pre>{move || data.get()}</pre>
            <button on:click=move |_| {
                    let mut sink = vec![];
                    let message = Encryptor::with_passwords(Message::new(&mut sink), Some("password"))
                        .build()
                        .unwrap();
                    let mut w = LiteralWriter::new(message).build().unwrap();
                    let _ = w.write_all(b"Hello world.");
                    let _ = w.finalize();
                    let b64 = general_purpose::STANDARD.encode(sink);

                    set_data.set(b64.clone());
                }
            >
                "Encrypt"
            </button>
        </div>
    }
}

pub fn main() {
    mount_to_body(|| {
        view! {
            <App />
        }
    })
}
1

There are 1 best solutions below

0
On

Unfortunately I don't particularly know much about encryption however this could help you:

  • Spawning a separate thread to handle the encryption

  • Make the server handle the encryption instead making use of server functions. Meanwhile you can show a loading html making use of Suspend and resource ( You can read more about this in the leptos docs )

  • Find another library to handle your encryption and or configure it accordingly for your needs