Sending Email from a Database afterInsert Hook

Hi guys,

I’m trying to send an email confirmation from a Database Hook. I made a new data.js file with afterInsert hook from the database.
This is the code (I know, I know) but I’m a bit confused on how to go about getting the data from the database to insert it into the email.

//data.js
	
import {sendEmail, sendEmailWithRecipient} from 'backend/newOrder';
import wixData from "wix-data";

export function Payments_afterInsert(item, context) {
	
	
$w.onReady(function () {
	wixData("Payments").afterInsert(sendFormData);
	
});

function sendFormData() {
	const subject = `Booking Confirmation`;
	const body = `Hi ${$w('#reviewClientName').value}, //get this from database
\nHurray! You are now part of our Digital Marketing Tips and Tricks Community. Please remember to Whitelist our Domain Name dudelemon.com and server.dudelemon.com so that all our Emails show up in your Inbox seamlessly.
\n
\nIf you have any questions, drop us an email at lemonteam@dudelemon.com
\n
\nThank you so much for your subscription,
\nDude Lemon Team`;
	const recipient = $w('#reviewEmail').text; //get this from database

	sendEmailWithRecipient(subject, body, recipient)
		.then(response => console.log(response));

	sendEmail(subject, body)
		.then(response => console.log(response));
}	
	

Any help ?

any genius out there ?

Hi,

$w is a function that is used only for your page code, meaning code that you write for a specific page. It has no meaning in data hooks, and will probably cause errors, so you need to remove it.
Please see the example from our docs on how to use the hook - basically, the item parameter you get in the function is the submitted data from the user that was inserted to the collection, so you can get info from it.
Docs: Hooks - Velo API Reference - Wix.com

Thanks Tomer!

So I guess this part is not gonna work as well ?

 //data.js
 
 import {sendEmail, sendEmailWithRecipient} from 'backend/newOrder';
 import wixData from "wix-data"; 
 
 export function Payments_afterInsert(item, context) {
  
    $w.onReady(function () { 
                 wixData("Payments").afterInsert(sendFormData);
   });
    function sendFormData() { 

$w.onReady ? does it have any work here in the hook ?

Can you point me in the right direction here ?

Start by removing the entire $w.onReady block.

Like this ?

//afterInsertPayments.js

import {sendEmail, sendEmailWithRecipient} from 'backend/newOrder';

export function Payments_afterInsert(item, context) {
	
	let hookContext = context;
	
	const subject1 = `Order ${item.orderId}`; //order id from database
	const body1 = `test`;
	const recipient = item.clientEmail; //client email from database

	const subject2 = `Order ${item.amount} `; //order id from database
	const body2 = `test`;

	sendEmailWithRecipient(subject1, body1, recipient)
		.then(response => console.log(response));

	sendEmail(subject2, body2)
		.then(response => console.log(response));

}