capacitor icon indicating copy to clipboard operation
capacitor copied to clipboard

fix(core): null-check before removing a listener

Open yukukotani opened this issue 4 years ago • 1 comments

remove would be undefined on calling PluginListenerHandle#remove before capacitor initialized. This causes remove is not a function. error.

This PR adds null-check before calling PluginListenerHandle#remove to avoid the error.

yukukotani avatar Jan 07 '22 12:01 yukukotani

Can you provide a sample app where the listener get removed before capacitor being initialized? In which platform does it happen?

jcesarmobile avatar Jan 10 '22 08:01 jcesarmobile

This is an issue for me (in that it causes noise in my application's logs).

I'm using Capacitor with a React app running on an iOS iPhone and on web. I use a useEffect hook to add listeners to a Capacitor plugin – something like:

useEffect(() => {
  const subscription = CapacitorAppPlugin.addEventListener('resume', onResume);
  return () => {
    subscription.remove();
  };
}, [onResume]);

(Happy to explain more if you're not familiar with React.) With React's strict mode enabled, this effect fires twice at launch, triggering the cleanup function, which hits this null remove issue.

I don't see any downside of adding this check – did you have something in mind?


For now, I'm working around this issue by changing the cleanup in the code above to:

          subscription.remove().catch((err) => {
            if (
              err instanceof TypeError &&
              err.message === "remove is not a function"
            ) {
              return;
            }
            throw err;
          });

davidisaaclee avatar Jun 28 '23 03:06 davidisaaclee

can you provide a sample app?

jcesarmobile avatar Jun 28 '23 08:06 jcesarmobile

I could not reproduce using https://github.com/ionic-team/capacitor-testapp as a base; if I find time, I'll try to reproduce again. (Is there a more barebones Capacitor + iOS sample project? For my purposes, something that already has Capacitor, iOS project, and ideally React.)

davidisaaclee avatar Jul 21 '23 14:07 davidisaaclee

Closing since there was no response and I've never seen this happen on any Capacitor app.

Please, when creating pull requests that fix an issue, make sure an issue already exists with an app that reproduces it so we can reproduce and verify the fix.

jcesarmobile avatar Jan 22 '24 14:01 jcesarmobile