Search code examples
rustsveltekittauri

How to pass a variable from backend to frontend in tauri


I have a Tauri app, with sveltekit as frontend. In the backend, I have a Websocket that collects some data in a variable. Now, I need to display this data in the frontend. I tried the emit_all event, and even something like this:

[...]   
 tauri::command::emit_all(
        tauri::Window::current(),
        "request",
        Some(json!({ "request": request })),
    )
    .expect("Failed to send request to frontend");
[...]   

And the code doesn't even compile. Is the approach wrong? I tried even other solutions (and I always have the listener in the frontend)


Solution

  • This is the shortest code I used that does what you want:

    fn function<R: tauri::Runtime>(manager: &impl Manager<R>) {
        manager.emit_all("event", ()).unwrap();
    }
    

    This is how you use it on the javascript side:

    import { listen } from "@tauri-apps/api/event";
    
    await listen("event", (event) => {})
    

    In the payload I would recommend you use serde_json directly, as that's what Tauri uses. But unless you post the actual compilation problem, we cannot know exactly what's wrong.