Display random pic from dataset

Hey guys,

I would like to show a random picture from my dataset, that stores a growing number of images.
The code I found online returns an error message. Do you know how I can fix the code or if there is an easier way to display a random picture?

My code:
// For full API documentation, including code examples, visit Velo API Reference - Wix.com
import wixWindow from ‘wix-window’ ;
import wixData from ‘wix-data’ ;

$w.onReady( async function () {

// Check the render env so this is just done once.
// Otherwise, server-side will render, and then the image
// switches to the image that the client-side rendered.
if (wixWindow.rendering.env === ‘browser’ || wixWindow.viewMode === ‘Preview’ ) {
let res = await wixData.query( “UploadedPictures” ).find();
let items = res.items;
let count = items.length; // how many images do we have?
let rnd = Math.floor(Math.random() * count);
$w( ‘#image1’ ).src = items[rnd].image; // get a random image
$w( ‘#image1’ ).show(); // image on page is hidden, we we now show it
}
});

Error message:
Loading the code for the 2 Rate page. To debug this code, open la9wx.js in Developer Tools.

Wix code SDK Warning: The src parameter of “image1” that is passed to the src method cannot be set to null or undefined.

Help is highly appreciated!

Hi,

Please check:

  1. res variable that return from the query() is not empty.

  2. items[rnd].image is a src.

  3. image field in your collection is type of “image”.

if you still get an error please contact us again,
Best,
Sapir

Thanks for the fast response.
I don’t know how to do 1. and 2.
Could you tell me how to do that?

  1. It is “image” type (see screenshot)

Hi,

Just add a console.log() and print those variables, you can see in inspect mode in your browser the result.

console.log(“res”, res);
console.log( “src”, items[rnd].imag );
in the browser-> right click->inspect-> console

Best,
Sapir

That’s what it says now. What do I do about it?
Do I need to define src? If yes, how?

Thank you!

Hi,

Can you send me a URL to your site?

Thanks,
Sapir

Sure:
https://adamspychala1989.wixsite.com/website

Hi

The problem is that the name of the image field in your database is ‘spacePicture’ so this is the key that include the src value in each item obj,
means you should write:

        $w('#image1').src = items[rnd].spacePicture;   // get a random image

That’s why you got undefined,

Best,
Sapir

Thank you :slight_smile: