Hello, I'm quite new to coding, so I need help getting the code below to be activated by a button.
import wixData from 'wix-data'; $w.onReady(function () { wixData.query("ideas") .find() .then((result) => { const shuffledArray = shuffleArray(result.items); console.log(shuffledArray) $w('#text2').text = String(shuffledArray[0].title); }) .catch((err) => { let errorMsg = err; }); }); $w.onReady(function () { wixData.query("challenge") .find() .then((result) => { const shuffledArray = shuffleArray(result.items); console.log(shuffledArray) $w('#text6').text = String(shuffledArray[0].title); }) .catch((err) => { let errorMsg = err; }); }); function getRandomIndex(min, max) { return Math.round(Math.random() * (max - min) + min); } function shuffleArray(dataArray) { for (let i = dataArray.length - 1; i > 0; i--) { let index = getRandomIndex(0, i); const temp = dataArray[i]; dataArray[i] = dataArray[index]; dataArray[index] = temp; } return dataArray; } Thanks a lot if you can help
First of all, always use only one $w.onReady per page code, and put everything you need inside.
Second, if you wish to run a query on button click do something like this:
import wixData from 'wix-data'; $w.onReady(() => { $w('#buttonbID').onClick(runQuery); }); function runQuery(){ wixData.query('Collection').find() .then(r => { const items = r.items; //Do whatever you want with the results }) }
If you wish to run 2 queries at once:
import wixData from 'wix-data'; $w.onReady(() => { $w('#buttonbID').onClick(runQuery); }); function runQuery(){ Promise.all([ wixData.query('Collection1').find(), wixData.query('Collection2').find() ]) .then(r => { const itmes1 = r[0].items; const items2 = r[1].items; //Do whatever you want with the results }) }