fix(core): null-check before removing a listener
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.
Can you provide a sample app where the listener get removed before capacitor being initialized? In which platform does it happen?
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;
});
can you provide a sample app?
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.)
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.