Failed to execute 'removeEventListener' on 'EventTarget': 2 arguments required, but only 1 present

1.8k views Asked by At

In my React app, I have the following useEffect and cleanup.

useEffect(() => {
    if (pageLoad) {     
        window.addEventListener('beforeunload', (e) => {
            localStorage.removeItem(SOME_KEY);
        });
        return () => {
            window.removeEventListener('beforeunload');
        }
    }
}, [pageLoad]);

However, I get the following error. Is there some issue with the removeEventListener ?

Failed to execute 'removeEventListener' on 'EventTarget': 2 arguments required, but only 1 present
1

There are 1 answers

0
Rahul Sharma On

You can pass same function to removeEventListener

useEffect(() => {
  if (pageLoad) {
    const cb = (e) => {
      localStorage.removeItem(SOME_KEY);
    };
    window.addEventListener("beforeunload", cb);
    return () => {
      window.removeEventListener("beforeunload", cb);
    };
  }
}, [pageLoad]);