How to get a value from a query as a variable

I’ve been having a problem that is starting to annoy me. I can’t seem to use the result of a query outside of the query. With some small code I accepted it and continued some coding in the results, but that is just not acceptable for what I want to write now. So how can I use the value out of the query? I’ve tried all sort of things and googled everything I could thing of but sadly I didn’t find a solution.

An example below. After pressing a button I set a string in x. Then with the query I look for a value in my database and set that as x. The console.log in the query gives the expected result. The console.log out of the query still gives the random string as result. I’m not sure if it is a timing issue, a scope issue or something else but I can’t image there not being a way to make this work! If anyone knows how to do that please let me know.

export function buttontest_click(event) {
var x
x=“change me!”

wixData.query( “Database” )
.eq( “title” , “row 4” ))
.find()
.then( (results) => {
let items = results.items;
let item = items[ 0 ];
let column2= item.column2;
x=column2
console.log(x)
})

console.log(x)

}

Hi,

This will seem counter-intuitive until it doesn’t, but the explanation is that the line at the bottom is evaluated before the query finishes. Have a look here:

https://www.wix.com/corvid/forum/tips-tutorials-examples/promises-promises

Hi :raised_hand_with_fingers_splayed:

You can declare a global variable without assigning any value to it, then reassign its value after the query, and you should be able to use its value globally.

Example:

let queryItems;

wixData.query('myCollection').find().then((result) => {
    queryItems = result.items;
})

Now you can use the query items or any value inside it anywhere as long as the declaration was made on the global scoop.

Alternatively, you can use Wix Storage API to store a value (only strings) and get it anywhere else including other pages on the website.

Hope this helps~!
Ahmad

I guess it is a timing issue. The order of which the console.logs trigger seems to indicate that. I’ll give the async await a try.

If I keep having problems then I’ll probably do something with a while loop and perhaps storing the value temporarily in a hidden text box or something like that. That would be ugly, but should at least work.