#Can not listen from backend in front-end.

37 messages · Page 1 of 1 (latest)

vivid spire
#

I'm trying to create an event listener for every command I have in Tauri(Rust). Also I'm not sure if this is the best pattern to follow.

The main problem is that when I emit an event from tauri, the front-end in react doesn't display anything.

JS:

useEffect(() => {
  const unlisten_register = listen('register', (event: any) => {
      console.log('REGISTER', event);
    });
    return () => {
      unlisten_register.then((unlisten) => unlisten());
    };
}, []);

This function is used in my custom command.
Rust:

async fn send_response(
    packet_name: &str,
    packet: BytesMut,
    window: tauri::Window,
) -> Result<(), Box<dyn Error>> {
    let _ = window.emit_all(
        packet_name,
        serde_json::to_string(&bincode2::deserialize::<InternalServiceResponse>(&packet)?)?,
    );
    Ok(())
}```
#
send_response("open_conn", packet, window.clone()).await
pine lake
#

the strings passed to listen and emit_all need to match for listen to receive an event

vivid spire
#

send_response("register", "Registerd".into(), window.clone()).await;

#
      console.log('REGISTER', event);
    });
    return () => {
      unlisten_register.then((unlisten) => unlisten());
    };```
#

I think they match

pine lake
#

hm, that should work

vivid spire
#
 if let Ok(_) = state
                .sink
                .lock()
                .await
                .as_mut()
                .unwrap()
                .send(bincode2::serialize(&payload).unwrap().into())
                .await
            {
                let _ = send_response("register", "Registerd".into(), window.clone()).await;

                println!("Register command {:?}", payload);
                Ok(())
            } else {
                println!("Something went wrong");
                Err("Unable to register".to_string())
            }```
#

I'm sending a payload to a TCP socket

#

The code isn't throwing any error but still the listener from JS doesn't work

#
  useEffect(() => {
    const gen = async () => {
      try {
        const uuid_value: string = await invoke('open_tcp_conn', {
          addr: '127.0.0.1:3000',
        });
        console.log('UUID', uuid_value);
        store.dispatch(setUuid(uuid_value));
      } catch (error) {
        console.log(error);
        setErr(error as string);
      }
    };
    gen();

    const unlisten_register = listen('register', (event: any) => {
      console.log('REGISTER', event);
    });
    return () => {
      unlisten_register.then((unlisten) => unlisten());
    };
  }, []);```
pine lake
#

an aside: does send_response have to be async?

vivid spire
#

no

#

I removed it

#

didn't fix

pine lake
#

you're getting Register command printed to the console yeah?

vivid spire
#

yes

pine lake
#

could the event be getting send before the listener has finished registering itself?

#

listen returns a promise that completes when it's ready to start receiving events

vivid spire
#

How can I check if so is happening?

#

The register event is triggered by a button click, I click it after the app is ready

pine lake
#

ah, i assumed the open_tcp_conn would be calling the event

vivid spire
#

Yeah, open_tcp_conn is calling a command and again the listener doesn't work

#
[✔] Environment
    - OS: Arch Linux Unknown X64
    ✔ webkit2gtk-4.0: 2.40.4
    ✔ rsvg2: 2.56.3
    ✔ rustc: 1.71.0 (8ede3aae2 2023-07-12)
    ✔ Cargo: 1.71.0 (cfd3bbd8f 2023-06-08)
    ✔ rustup: 1.26.0 (5af9b9484 2023-04-05)
    ✔ Rust toolchain: stable-x86_64-unknown-linux-gnu (environment override by RUSTUP_TOOLCHAIN)
    - node: 20.4.0
    - yarn: 1.22.19
    - npm: 9.8.1

[-] Packages
    - tauri [RUST]: 1.4.1
    - tauri-build [RUST]: 1.4.0
    - wry [RUST]: 0.24.3
    - tao [RUST]: 0.16.2
    - @tauri-apps/api [NPM]: 1.4.0
    - @tauri-apps/cli [NPM]: 1.4.0

[-] App
    - build-type: bundle
    - CSP: unset
    - distDir: ../out
    - devPath: http://localhost:1420/
    - framework: React (Next.js)
    - bundler: Webpack```
#

Open TCP conn

let packet = bincode2::deserialize::<InternalServiceResponse>(&packet)
                    .map_err(|err| err.to_string())?;

                if let InternalServiceResponse::ServiceConnectionAccepted(accepted) = packet {
                    let service_to_gui = async move {
                        while let Some(packet) = stream.next().await {
                            if let Ok(packet) = packet {
                                if let Err(e) = send_response("open_conn", packet, window.clone()) {
                                    error!(e)
                                }
                            }
                        }
                    };

                    tauri::async_runtime::spawn(service_to_gui);
                    Ok(accepted.id)
pine lake
#

if you've got a listen("open_conn", ...) in your frontend then idk idk why it wouldn't be working

vivid spire
#

I'm not getting a listen("open_conn", ...), I'm returning an Ok(accepted.id) it being the single field in the struct I get

#

but maybe a listen is an promise

#

but my useEffect is an async fn

#

ohh

#

it's not

pine lake
#

listen is a promise yeah but that's fine, it'll set itself up even if you don't await it

#

as long as it finishes setting up before you do other stuff

#

which you can't guarantee unless you await it

vivid spire
#

send_response() doesn't work but window.emit() works

#

that means there is something wrong with the send_response() function

#

@pine lake thank you for guidance