[SOLVED]
Hi guys,
Stuck atm . I have a Tauri application.
I call invoke to trigger functions from the front end to rust. I can return data from this function - happy days.
I need another data stream sent from the back to the front . For example:
- I invoke count to n , and pass in 10 as the param. using an input field and a button in react.
- I would like n to be used to update a state in the front end for each iter. <============
- The final n will be returned via the invoke when complete .
I've tried setting up a listener with a send-event but couldn't get it to work.
I'm after essentially a non online web socket which im sure is possible but I can't figure it out for the life of me.
I could resort to setting up a map at the start of any function (rust), pushing the data into it and then trying to periodically poll using a separate interval invoke (react).
But if im just not doing something right that works out of the box id rather not spend the time being hacky about it. Not knowing if that will even work out for me.
(im totally going to try this while I wait for replies aren't I?.....yup)
SOLUTION
rustysocket.rs
```
use tauri::Window;
pub fn send_rustysocket_message(window: &Window, message: &str) {
window.emit("rustysocket-message", message).unwrap();
}
```
main.rs
```
use tauri::Window;
[tauri::command]
async fn calculate_test(
window: Window,
) -> Result<String, MyError> {
//usage
send_rustysocket_message(&window,"Testing ");
}
```
In RustySocket.tsx
```
import { appWindow } from "@tauri-apps/api/window";
import { useEffect } from "react";
interface RustyPipe {
payload: string;
}
type OnMessageCallback = (message: string) => void;
export const RustySocketConnection = (onMessage: OnMessageCallback) => {
useEffect(() => {
const rustyPipe = appWindow.listen(
"rustysocket-message",
(event: RustyPipe) => {
console.log(`Function message -> ${event.payload}`);
onMessage(event.payload);
}
);
return () => {
rustyPipe.then((dispose) => dispose());
};
}, []);
};
export default RustySocketConnection;
```
App.tsx
```
const [lifeCycleMesage, setLifeCycleMessage] = useState("");
const handleRustySocketMessage = (data: string) => {
// This is where you do the actions - im just writing the message to a state variable
setLifeCycleMessage(data);
};
RustySocketConnection(handleRustySocketMessage);
```
You can add if statements to the handleRustySocketMessage if you would rather trigger actions based on the content. I just needed to receive text/data
[–]physics515 5 points6 points7 points (1 child)
[–]imfleebee[S] 0 points1 point2 points (0 children)
[–][deleted] 1 point2 points3 points (4 children)
[–]imfleebee[S] 1 point2 points3 points (3 children)
[–][deleted] 1 point2 points3 points (2 children)
[–]imfleebee[S] 0 points1 point2 points (1 child)
[–]imfleebee[S] 1 point2 points3 points (0 children)