Coding Question? Can you turn a query into a function?

Hello all,
Quick question for you all regarding database queries. I’m sure this is a basic coding concept but is there a way to put this

function query() {

	let currentUser = wixUsers.currentUser;
	currentUser.getEmail().then(email => {
		wixData.query('Members').eq('email', email).find()
			.then((results) => {
				let item = results.items[0];
			});
	});
}

Is there a way to save this process and use the “item” variable from this query in another function and then use it within other functions like for example

updateFields(query);

With query replacing the requirement to have to write the query as above and essentially transferring the “item” variable from the query?

Thanks much.

Kind regards,

Chris

Hi Chris!

In order to use a variable/value from one function in another you need to return it.
In the case that you described there is a use of promises (read more about promises here ) and in such case a variable won’t be able to return until the promise is resolved.

Your function should look like this:

import wixData from 'wix-data';

function query() {
	return new Promise(resolve => {
		let currentUser = wixUsers.currentUser; 
		currentUser.getEmail()
		.then(email => { 	
		      wixData.query('Members')
		      .eq('email', email)
		      .find() 
		      .then((results) => {
		     	    let firstItem = res.items[0];
			    resolve(firstItem);
			});
	});
}

Please inform me if something isn’t working as you plan.
Hope it helps.
Best of luck!

Doron. :slight_smile: