Display A Random Text?

So I’ve been looking through tutorials and they all just don’t work. I just can’t figure this out. I’m trying to make it so every time you visit/refresh a certain page, it shows different text.

This is the code I’m trying to use from these tutorials- It’s not showing any errors, but it’s not working.

import wixData from ‘wix-data’ ;
let randomActivate = true ;

wixData . query ( ‘dataset1’ ). limit ( 25 ). find (). then ( ( res ) => {
let items = res . items ;
let randomNum = Math . floor ( Math . random () * items . length ) - 25 ;
let randomItem = items [ randomNum ];
console . log ( randomItem );
$w ( “#text213” ). text = randomItem . value
});

Any help with this?

Hi, Why you’re substracting the 25 from the random number? Because by this way you can get a negative value. Which unable to get the item. Also, If you don’t getting an error, then try:

  1. Add console.log() to check the query items.

  2. Add console to check the random value.

  3. Check you’re getting the random item in console.

  4. Assing string value to the text. Use .toString()

If still unresolved, I request you to send the code & console screenshot.

 let randomNum = Math.floor(Math.random() * items.length);

Meaning, get rid of the -25

@jonatandor35 Even after doing that it’s not working. It just keeps giving me the same line of text.

@mysterypotatoheads Be sure there’s a value for this item + check the console for errors

@jonatandor35 There are no errors in console. How do I check for a value of the item??

Got it working!

@mysterypotatoheads would you mind sharing the working code?

@prestonkelpiek9 This is the code that was used:

import wixData from 'wix-data';

$w.onReady(function () {
        wixData.query("DatabaseID")
            .find()
            .then((result) => {
                const shuffledArray = shuffleArray(result.items);
                console.log(shuffledArray)
                $w('#textID').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;
}

You will need to change DatasbaseID to the ID of your database. And textID will need to change to the ID of the text you want to display the random text within.

@noahlovell thankyou!