How to make repeater show randomized items from dataset?

I have a recipes dynamic page that successfully shows each recipe values on the page. But i also need a repeater to show/recommend other recipes from the dataset randomly. I can manage it showing the recipes in a static order but I need it to change/randomize on each recipe page.

Could use some help, thanks.

1 Like

Hey Yigit,

Thanks for providing an early morning challenge. After considerable thought and several aspirin, I think I’ve got a way you can access recipes randomly.

Using the API wix-data.WixDataQuery , a little bit of creativity, duct tape, and WD-40, you should be able to cobble together a random access query to your database. Try something like this:


import wixData from 'wix-data';

// ...

let max = numberRecipes - 3;
let skip = Math.floor(Math.random() * max) + 1;

wixData.query("recipes")
  .ascending("title")
  .skip(skip)
  .limit(3)
  .find()
  .then( (results) => {
    let items = results.items;
    console.log(items);  // take a look at what we got
    $w("#recipeRepeater").data = items; // add data to our repeater 
    let recipe1 = items[0];
    let recipe2 = items[1];
    let recipe3 = items[2];
  } )
  .catch( (error) => {
    let errorMsg = error.message;
    let code = error.code;
  } );

In the above example, I skip a random number of items before returning the three that we want. The skip value is calculated to be in the range between 1 and the number of recipes minus 3.

Of course, there are many permutations that are possible. You can also randomly switch between .ascending() and .descending(), which column to sort, etc.

This should give you good start.

Have fun and bon appetit,

Yisrael

Hey Yisrael,

Thank you for the quick reply! :slight_smile:

Unfortunately I have so little knowledge on coding. I did understand the logic behind the code you have given but I have no idea how to apply it to the repeater. I mean, I believe I have to call the repeater to do these things with $w(“repeater1”) at some point but thats about it :confused:

A little more help would be much appreciated !

Start with the documentation on $w.Repeater . You will find a clear and concise explanation on all of the features and methods, along with plenty of examples on how they’re used.

Take a look at the sample code in my previous post. I added a line that adds the data retrieved from the database to the repeater:

    $w("#recipeRepeater").data = items; // add data to our repeater 

I would suggest just playing around with the repeater and the database query in the editor. Since you already managed to display recipes in static order, all you need to do now is to add in the random query.

You will also notice that I added the following line of the code to my sample:

    console.log(items);  // take a look at what we got 

Remember this: console.log() is your friend - your very good friend. Use it whereever you want to see if you have the expected values. In this case, console.log() should display information of the three recipes in the Developer console pane of the editor.

Yisrael

Hey,

Ive been at it for a while now, but no luck at all. I cant understand where the code is connected to the dataset from and let recipe1 = items[0]; let recipe2 = items[1]; let recipe3 = items[2]; this part is giving an “item unread” error.

I know some names are stand-ins for the actual ones but got me really confused. Do need to connect the repeater to the dataset from the repeater itself (clicking the connect to dataset button)? I said i managed to show recipes in a static order but I only managed that by clicking this button and selecting the right field from the dataset. No coding required. So Im really really lost right now.

Hey Yigit,

Here is my original chunk of code that’s been enhanced to show how to get the repeater to work. The code does the following (each point identified in the code):

  1. Get a random skip number.

  2. Query the database and get our random 3 recipes.

  3. Create a repeater data object from our retrieved data

  4. Set the repeater data property with our data object

  5. Add an .onItemReady() method to handle the repeated items.

import wixData from 'wix-data';

$w.onReady(function () {

	// 1) get a random skip number
	let max = numberRecipes - 3;
	let skip = Math.floor(Math.random() * max) + 1;

	// 2) query the database and get our random 3 recipes
	wixData.query("recipes")
	.ascending("title")
	.skip(skip)
	.limit(3)
	.find()
	.then( (results) => {
		let items = results.items;
		// 3) create a repeater data object from our retrieved data
		let picData = [
			{
				"_id":items[0]._id,
				"image1":items[0].picture
			},
			{
				"_id":items[1]._id,
				"image1":items[1].picture
			},
			{
				"_id":items[2]._id,
				"image1":items[2].picture
			}
		];

		// 4) set the repeater data property with our data object
		$w("#repeater1").data = picData; // add data to our repeater 
	} )
	.catch( (error) => {
		let errorMsg = error.message;
		let code = error.code;
	} );
	
	// 5) method to handle each repeated item
 	$w("#repeater1").onItemReady( ($w, itemData, index) => {
 		// all we do here is set the repeated image from our data
 		const repeatedImage = $w("#image1");
  		repeatedImage.src = itemData.image1;
   		console.log(repeatedImage);
   
   		// you can do a whole lot more in this routine:
   		// - handle other fields or elements
   		// - add an onClick() handler
   		// - handle selected repeat items
   	});
});

This is a very simple example which just shows the basics. Refer to the documentation on $w.Repeater, be creative, and…

Have fun,

Yisrael

1 Like

Hi Yisrael,
I am trying to accomplish this same thing. The number of items to display is fairly large for some of my categories and when I uploaded it to the database a lot of the same type of item was uploaded at once. So the category is not showing a true mix of items. You can see a good example here. https://www.easternstyles.com/artificial-floral-garden

It has about 100-150 items in that Category. I am trying to randomly mix the items. Any suggestions?

Note I have copied your code from above and changed a couple things but I have no idea if what I did is correct. See below

import wixData from ‘wix-data’;

$w.onReady(function () {

let max = - 3; 
let skip = Math.floor(Math.random() * max) + 1; 

wixData.query("Item") 
.ascending("title") 
.skip(skip) 
.limit(3) 
.find() 
.then( (results) => { 
	let items = results.items; 
		let picData = [ 
		{ 
			"title":items[0]._id, 
			"image":items[0].picture 
		}, 
		{ 
			"title":items[1]._id, 
			"image":items[1].picture 
		}, 
		{ 
			"title":items[2]._id, 
			"image":items[2].picture 
		} 
	]; 

		$w("#repeater3").data = picData;  
} ) 
.catch( (error) => { 
	let errorMsg = error.message; 
	let code = error.code; 
} ); 

 	$w("#repeater3").onItemReady( ($w, itemData, index,) => { 
	 		const repeatedImage = $w("#image"); 
	repeatedImage.src = itemData.image; 
	console.log(repeatedImage); 

   	}); 

});

Hi,

Any updates on this?

Hi Nathan,

I can’t really evaluate your code since I don’t know exactly what you have on the page, but I see one glaring error:

let max = - 3;

This line of code sets the maximum number of recipes at -3.

My original line of code was:

let max = numberRecipes - 3;

You will need to provide the number of recipes in the database collection in order to get a random skip number. You can query the the size of the collection something like this:

wixData.query("Item")
    .count()
    .then( (num) => {
    console.log(num); // num is the size of the collection
} )
.catch( (error) => {
    let errorMsg = error.message;
    let code = error.code;
} );

Another thing… Is Item the name of your database collection? You use Item as your collection name in your query:

wixData.query("Item")

I hope these comments help.

Yisrael

Hi Yisrael,
Thank you for responding. To answer your questions Yes, Item is the name of my Database Collection.

Just to clarify the database collection you are referring to at the start of your post would be all the products in my database collection or only the products that are relevant for this Category Page? https://www.easternstyles.com/artificial-floral-garden

I have a many different products 1000 + so I had to split them up into different categories

When I refer to “collection”, I mean the database collection that you are performing the query on.

Hi Yisrael,
This is a bit confusing for me. Really not an expert in code. This is the code I currently have on the page

import wixWindow from ‘wix-window’;
$w.onReady(function () {
if(wixWindow.formFactor === “Mobile”){
$w(“#image21”).hide();
$w(“#box3”).hide();
$w(“#line6”).hide();
}
});

import wixData from ‘wix-data’;

export function Artificialflowers_click() {
$w(‘#dataset1’).setFilter(
wixData.filter()
.contains(‘subCategory’, “Artificial Flowers”)
);
}

export function Floraldecorations_click() {
$w(‘#dataset1’).setFilter(
wixData.filter()
.contains(‘subCategory’, “Floral Decorations”)
);
}

export function Artificialplants_click() {
$w(‘#dataset1’).setFilter(
wixData.filter()
.contains(‘subCategory’, “Artificial Plants”)
);
}

export function Flowerpots_click() {
$w(‘#dataset1’).setFilter(
wixData.filter()
.contains(‘subCategory’, “Flower Pots”)
);
}

export function Floralaccessories_click() {
$w(‘#dataset1’).setFilter(
wixData.filter()
.contains(‘subCategory’, “Floral Accessories”)
);
}

export function Gardentools_click() {
$w(‘#dataset1’).setFilter(
wixData.filter()
.contains(‘subCategory’, “Garden Tools”)
);
}

export function Artificialfloralgarden_click() {
$w(‘#dataset1’).setFilter(
wixData.filter()
.contains(‘topCategory’, “Artificial Floral & Garden”)
);
}

export function button15_onClick(event) {
$w(‘#verticalMenu2’).show();
$w(‘#image21’).show();
$w(‘#box3’).show();
}

export function box3_onmouseOut(event) {
$w(‘#verticalMenu2’).hide();
$w(‘#image21’).hide();
$w(‘#box3’).hide();
}

This is the URL for that page https://www.easternstyles.com/artificial-floral-garden

I need some clarification as to how to go forward.

No updates…

@yisrael-wix

See my posts above. The code that I posted demonstrates how to do this.

2020 new update plz this is not work
plz new update

Please add your own issue into a new post instead of bumping up an old post. Explain what you are trying to do, what works, and what doesn’t. Also, add any code in a code block as stated in the Forum Guidelines.

This post is an old post and is being closed.