query an image from a dataset

Hi :slight_smile:

I am trying to call an image from a database that the user have created and stored into ‘Purchase’ database, using data wix query, and then save the image src into a new variable., this is my code so far:

import wixData from ‘wix-data’;
import wixUsers from ‘wix-users’;

$w . onReady ( function () {

id  =  wixUsers . currentUser . id ; 
$w ( "#dataset4" ). setFilter ( wixData . filter (). eq ( 'user' ,  id )) 

let showImage = wixData . query ( “Purchase” )
. eq ( ‘user’ , id )
. find ()
. then ( ( results ) => {
let item = results . items [ 3 ];
let image = item . images ;
$w ( ‘#image1’ ). src = image ;

} );

});

i need to change the image that is on the page to the one from the database, can someone tell me if my code is correct or should i try other method?

Hi! Instead of using a hardcoded index of 3, you should use a loop to iterate over the results.items array and update the image for each item. You may want to add a check to make sure that the results object is not empty before attempting to access the items array.

Try out:

wixData.query("Purchase")
  .eq('user', id)
  .find()
  .then( (results) => {
    if (results.items.length > 0) {
      for (let i = 0; i < results.items.length; i++) {
        let item = results.items[i];
        let image = item.images;
        $w('#image1').src = image;
      }
    }
  })
  .catch( (error) => {
    // handle error
  });