plugins-workspace icon indicating copy to clipboard operation
plugins-workspace copied to clipboard

[deep-link][v2] onOpenUrl Listener is being triggered when mounting even if the even was already processed

Open nicolaspapp opened this issue 4 months ago • 1 comments

Hey there, I am trying to setup the onOpenUrl listener on my Tauri app, which is using React and React Router on the FE.

I have setup a single hook to hear on the frontend for the deep links event and generate a redirect based on the information. What I see is that when the redirect is triggered, a new listener will be mounted and I will get the deep link event again.

I have already checked that the issue is not the double mounting React does on dev builds.

Is this a bug? Or I am missing something?

Including a small snippet of the hook:

import { onOpenUrl } from "@tauri-apps/plugin-deep-link";
import { useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";

export const UseDeepLinkUrl = () => {
  const navigate = useNavigate();
  const isListenerRegistered = useRef(false);

  useEffect(() => {
    if (isListenerRegistered.current) {
      return;
    }

    const unlisten = onOpenUrl((url: string[]) => {
      console.log("url", url);
      const path: string = url[0].split("://")[1];
      console.log("Setting link to:", path);
      navigate(path);
    });
    isListenerRegistered.current = true;

    return () => {
      unlisten.then((f) => {
        console.log("unlisten", f);
        isListenerRegistered.current = false;
        return f();
      });
    };
  }, []);

  return null;
};
export default UseDeepLinkUrl;

nicolaspapp avatar Oct 03 '24 17:10 nicolaspapp