How do i send an event once the app is loaded? #10581
-
I'm building an app in which i want to load state from the system files once it's launched and display it to the frontend and in the frontend users can make changes and that should call rust to make changes to the filesystem so it's a two way data exchange, i'm trying to use events but i'm having a hard time to get this to work, this is what i have // +page.svelte
<script lang="ts">
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { onDestroy, onMount } from "svelte";
let unlisten: UnlistenFn;
onMount(async () => {
console.log("Listening to `test_event`");
unlisten = await listen("test_event", (event) => {
console.log("EVENT RECEIVED!!");
console.log(event);
});
});
onDestroy(() => {
unlisten();
});
</script>
<div class="container">
<h1>Welcome to Tauri!</h1>
</div> // lib.rs
use tauri::{Emitter, Manager};
use {
std::thread::{sleep, spawn},
std::time::Duration,
};
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.setup(|app| {
app.emit("test_event", "1st event").unwrap();
let copy = app.app_handle().clone();
spawn(move || {
sleep(Duration::from_secs(10));
copy.emit("test_event", "2nd event").unwrap();
});
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
} I am able to see the 2nd event but not the 1st and i'm guessing that happens because the 1st event is emitted before the frontend gets setup? How can i make this work, or is there a better way to transfer data from backend to frontend and vice-versa without using events? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Correct. There really isn't anything we can do in Tauri to automatically detect when the frontend is fully ready so you'd have to do it yourself. You could either send a "ready" event from your frontend and wait for that on the rust side (likely storing it somewhere) or use tauri commands instead of events to request the data from the frontend instead of pushing it from the backend (of course that depends on the actual usecase) |
Beta Was this translation helpful? Give feedback.
Correct. There really isn't anything we can do in Tauri to automatically detect when the frontend is fully ready so you'd have to do it yourself. You could either send a "ready" event from your frontend and wait for that on the rust side (likely storing it somewhere) or use tauri commands instead of events to request the data from the frontend instead of pushing it from the backend (of course that depends on the actual usecase)