how do I avoid listening to a same event twice? #5194
-
Hello, yesterday I managed to make first tauri-app by following the official guide. But after that, when I tried letting Rust backend emit event to trigger Next.js frontend, the frontend captured two same copies of the event. The listen and emit looks like this: // frontend side
function App() {
// . . .
useEffect(() => {
//listen to a event
listen("event-name", (e) => {
console.log(e.payload);
});
// invoke a Rust function to start a loop for periodically emitting event.
start_backend_emitting_loop();
}, [] );
// . . .
return(
// . . .
)
} // Rust side
#[tauri::command]
async fn start_backend_emitting_loop(window: tauri::Window) {
// . . .
loop {
window
.emit(
"event-name",
Payload {
message: format!("{} sent from Rust", ms).into(),
},
)
.unwrap();
}
} From the console and terminal I saw that frontend is triggered twice on a single emit. Am I using a wrong way to listen? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Are you using strict mode of react? Because that makes components to render twice. Please put a console.log(Math.random()) in useEffect and check if you get 2 logs or 1: useEffect(() => {
console.log(Math.random());
}, []); |
Beta Was this translation helpful? Give feedback.
-
Tauri's Events work similar to browser native events, which means that you need to unlisten to them on unMount. useEffect(() => {
//listen to a event
const unlisten = listen("event-name", (e) => {
console.log(e.payload);
});
// invoke a Rust function to start a loop for periodically emitting event.
start_backend_emitting_loop();
return () => {
unlisten.then(f => f());
}
}, [] ); Note that P.S. if your component can't realistically unMount (betting on that is really risky btw*), then check abisar's response and disable strict mode. What i mean with it being risky:
|
Beta Was this translation helpful? Give feedback.
Tauri's Events work similar to browser native events, which means that you need to unlisten to them on unMount.
Note that
start_backend_emitting_loop()
needs some test on the backend too, so you don't end up starting that loop multiple times.P.S. if your component can't realistically unMount (betting on that is really risky btw*), then check abisar's response and disable strict m…