This post for Corvid beginners explains how to populate a repeater with database collection content using code.
Note: You can also populate a repeater without any code using a dataset.
To populate your repeater:
- Query the database collection.
- Set the queried data as your repeater’s data.
- Specify which fields of the queried collection data populate each element in your repeater.
Write the code
import wixData from 'wix-data';
- Then we’ll query our database collection. You can optionally add filters or sort the query if you want to refine the data that appears in the repeater.
wixData.query("MyCollection")
.find()
.then((results) => {
if (results.totalCount > 0) {
console.log("Query results:", results.items);
}
})
.catch((error) => {
console.log("Error:", error.message);
});
- Next we set the the results of the query as the repeater’s data.
$w("#myRepeater").data = results.items;
Setting a repeater’s data adds new items to the repeater and triggers the repeater’s onItemReady() event handler.
- Let’s add the code for the onItemReady() function. onItemReady() is used to apply the repeated item’s data to the properties of the repeated elements. In the following code, title, description, image, and url are field keys from the MyCollection database collection.
$w("#myRepeater").onItemReady(($item, itemData, index) => {
$item("#myTitleText").text = itemData.title;
$item("#myDescriptionText").text = itemData.description;
$item("#myImage").src = itemData.image;
$item("#myButton").link = itemData.url;
});
This code loops through each repeater item and sets the properties of the repeated elements from the data for that item. We use the $item selector instead of $w. $item is used with repeaters to select elements in the current repeater item.
Note that you must call onItemReady() before you set the repeater data.
So let’s put it all together. We’ll place our code in the onReady() function so it’ll run when the page loads.
import wixData from 'wix-data';
$w.onReady(function () {
$w("#myRepeater").onItemReady(($item, itemData, index) => {
$item("#myTitleText").text = itemData.title;
$item("#myDescriptionText").text = itemData.description;
$item("#myImage").src = itemData.image;
$item("#myButton").link = itemData.url;
});
wixData.query("MyCollection")
.find()
.then((results) => {
if (results.totalCount > 0) {
$w("#myRepeater").data = results.items;
}
})
.catch((error) => {
console.log("Error:", error.message);
});
});