manuelBetancurt
manuelBetancurt

Reputation: 16138

react native unsubscribe event listener

I have a react native component with two event listeners for linking and for dynamicLinks, how do I unsubscribe for both using hooks?

  useEffect(() => {
    // Update the document title using the browser API
    if (Platform.OS === "ios") {
      SecurityScreen.enabled(true);
    }
    // global.perra = "a";

    usingAlternativeAPI();

    Linking.addEventListener("url", deepLinkHandler);

    const unsubscribe = dynamicLinks().onLink(handleDynamicLink);
    // When the component is unmounted, remove the listener
    return () => unsubscribe();

  }, []);

Upvotes: 1

Views: 1388

Answers (3)

Charana Amarasekara
Charana Amarasekara

Reputation: 76

At the moment the documentation points to do this way,

 useEffect(() => {
   const unsub = Linking.addEventListener("url", ({ url: _url }) => {
                 setUrl(_url);
   });
   return unsub.remove();
 }, []);

Upvotes: 1

Arbnor
Arbnor

Reputation: 2352

Linking lib has a removeEventListener() function you can call with passing the url event type and the handler. This code should work.

     useEffect(() => {
        // useEffect code here
        return function cleanup() {
          unsubscribe();
          Linking.removeEventListener("url", deepLinkHandler);
        };
      }, []);

Upvotes: 2

Calix
Calix

Reputation: 356

Have you tried this before?

useEffect(() => {
    // Update the document title using the browser API
    if (Platform.OS === "ios") {
      SecurityScreen.enabled(true);
    }
    // global.perra = "a";

    usingAlternativeAPI();

    const un = Linking.addEventListener("url", deepLinkHandler);

    const unsubscribe = dynamicLinks().onLink(handleDynamicLink);
    // When the component is unmounted, remove the listener
    return () => { 
         unsubscribe();
         un()
         }

  }, []);

Upvotes: 1

Related Questions