Search code examples
javascriptreactjsonbeforeunload

beforeunload event on component which created by map


hello everyone im trying to send request to backend while closing the browser. I have a simple code.

Parent:

/*codes*/

return(
<>
{items.map(item => <div key={item.key}>
<Child item={item} />
</div>)}
</>
);

Child

    /*codes*/
    
        useEffect(() => {
        const handleWindowClose= () => {
          post(props.item.id,props.item.status)
        };
        window.addEventListener('beforeunload', handleWindowClose);
        return () => {
          window.removeEventListener('beforeunload', handleWindowClose);
        };
      }, []);
/*more codes*/

but it seems that only 1 element sending request others cant.

how to fix this ? maybe an idea.


Solution

  • Seems like the child components are using the same event listener callback function.

    You need to modify the event listener callback function specifying the item:

    useEffect(() => {
      const handleWindowClose = () => {
        post(props.item.id, props.item.status);
      };
    
      window.addEventListener('beforeunload', handleWindowClose);
    
      return () => {
        window.removeEventListener('beforeunload', handleWindowClose);
      };
    }, [props.item.id, props.item.status]); //add item properties