I use an item on my page, #hiddenEmail to retrieve a record from the collection ‘authorpages’:
export function buttonLikes_click(event) {
wixData.query( ‘authorpages’ )
.contains( ‘email’ , $w( “#hiddenEmail” ).value)
.find()
let itemObj2 = $w( “#dataset2” ).getCurrentItem();
console.log ( 'page email = ’ , $w( “#hiddenEmail” ).value);
console.log ( 'retrieved email = ’ , itemObj2.email);
However, the ‘find’ isn’t working and I can’t see why. The console log shows “page email” is correct, but “retrieved email” just comes from the most recently created record in the collection.
Help much appreciated.
In order to retrieve the record using a dataset, you need to filter the dataset. You are currently trying to filter the collection using wixData.query , but this does not affect the dataset that you are using.
See the dataset.setFilter() API for details on how to filter a dataset.
Note : if you want to perform a query directly on the collection using WixDataQuery , you need to handle the returned Promise. See the examples in the find() API . Refer to the following information about Promises:
Thanks. I’ve changed the code to this:
export function buttonLikes_click(event) {
$w( “#dataset2” ).setFilter(wixData.filter()
.contains( “email” , $w( “#hiddenEmail” ).value));
let itemObj2 = $w( “#dataset2” ).getCurrentItem();
console.log ( 'page email = ’ , $w( “#hiddenEmail” ).value);
console.log ( 'retrieved email = ’ , itemObj2.email);
But it’s doing the same thing - i.e. I’m still getting the last created record in the collection.
Do I have to do something more to make the correct record current?
The dataset setFilter() function returns a Promise, which you will have to handle as shown in the examples from the documentation.
You want something like this:
$w("#dataset2").setFilter( wixData.filter()
.contains("email", $w("#hiddenEmail").value))
)
.then( () => {
console.log("Dataset is now filtered");
let itemObj2 = $w("#dataset2").getCurrentItem();
console.log ('page email = ', $w("#hiddenEmail").value);
console.log ('retrieved email = ', itemObj2.email);
} )
.catch( (err) => {
console.log(err);
} );
Note: I have not tested the above code as I don’t know the other details of your site. This should get you going in the right direction.
Again, please refer to the following information about Promises:
Yes, it just needed the promise; now it works fine.
Many thanks!