Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store data in firestore when Browser Tab is closed or the route is changed (react JS)

 const handleDraftContracts = async () => {
    console.log('/bruhhhhhhandleDraftContract');
    const paragraphRef: string | any = document.getElementById('contract');
    const contractDetails = {
      contractName: 'House Rental',
      states: {
        amount: amount,
      },
      content: paragraphRef?.textContent,
    };
    await makeDraftContract(contractDetails);
  };

  useEffect(() => {
    console.log('///////I am hreeeee');
    window.addEventListener('onbeforeunload', (env) => {
      handleDraftContracts();
    });
    return () => {
      console.log('///////removing');
      window.removeEventListener('onbeforeunload', handleDraftContracts);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

firestore.js

// make Draft Contracts
export async function makeDraftContract(contractDetails: object | any) {
  try {
    console.log("making a draft contract", contractDetails);
    const draftContractRef: any = collection(db,"makeDraftContracts"); 
    let contract = await addDoc(draftContractRef, contractDetails);
    console.log("./////////makeDraftContract", contract);
  } catch (error) {
    console.log('////errror in contract Hanlder', error);
  }
}

I want to call my handleDraftContracts method whenever user closes the tab or changes the route. I am using onbeforeunload event. The handleDraftContracts is getting called but the tab unloads before Firestore could update the collection. How can I get around this that as the user closes the tab or move to a new route, my firestore method get executed first then the tab gets unloaded ?

like image 754
Abdullah Ch Avatar asked Dec 12 '25 04:12

Abdullah Ch


1 Answers

Try with Beacon api https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API

as 'onbeforeunload' cannot make sure you request to server has been made and requests can slow down the browser

componentWillUnmount is like that one, cannot to make long running script.

like image 154
Hans Murangaza DRCongo Avatar answered Dec 14 '25 00:12

Hans Murangaza DRCongo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!