notice the arrow functions in both document.addEventListenerand removeEventListener calls - you are creating new functions on the fly.
when addEventListener is called here, a new function will be created, and provided as event handler.
when removeEventListener is called, again, another new function will be created, and provided as the reference to which function that needs to be removed from the listeners.
whenever we write () => {} we are creating a new function, and even if the code is exactly the same, javascript will treat them as totally different entities.
To fix this, we should only create the callback once, and pass the reference to that function to all 4 calls:
useEffect(()=>{// create the event handler and save its reference to const closeModalconstcloseModal=(e)=>{closeModalFunction(e,closePriceHistoryModal);};document.addEventListener('mousedown',closeModal);// pass reference to the calldocument.addEventListener('keydown',closeModal);// referencing the same functionreturn()=>{document.removeEventListener('mousedown',closeModal);// same referencedocument.removeEventListener('keydown',closeModal);// same reference};},[closePriceHistoryModal]);
Oh I see... this is the callback you were talking about!!! amazing... the weird thing is it only happens to this specific modal so I didnt notice until now! Let me try this and get back to you
AMAZING IT WORKED I added the key down option too.. WOW this lesson was awesome thank you so much... if you ever want free mcdonalds or food I gotchu my friend!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
here is the code for close modal function that I wrote
and this works for all the modals except specifically this one
![thepracticaldev.s3.amazonaws.com/i...]
Right, so in your effect hook, the event listeners are never cleaned up.
you have something like this:
notice the arrow functions in both
document.addEventListener
andremoveEventListener
calls - you are creating new functions on the fly.when
addEventListener
is called here, a new function will be created, and provided as event handler.when
removeEventListener
is called, again, another new function will be created, and provided as the reference to which function that needs to be removed from the listeners.whenever we write
() => {}
we are creating a new function, and even if the code is exactly the same, javascript will treat them as totally different entities.To fix this, we should only create the callback once, and pass the reference to that function to all 4 calls:
Oh I see... this is the callback you were talking about!!! amazing... the weird thing is it only happens to this specific modal so I didnt notice until now! Let me try this and get back to you
AMAZING IT WORKED I added the key down option too.. WOW this lesson was awesome thank you so much... if you ever want free mcdonalds or food I gotchu my friend!