Beginner question: This code seems to work. Have I missed anything?

I’m trying to learn both Javascript and Velo by writing code to add functionality to a site of my own. I’ve just written a next page / previous page function that appears to work, but I’d really appreciate it if someone with better skills would let me know if I’ve missed something important in it.

The site has a collection of news stories and includes a stories archive page that uses a repeater to display them.

A dataset controlling the repeater limits the repeater to twelve stories. I want users to be able to page forward and backward through the stories, twelve stories at a time.

I’ve added a ‘next’ button and a ‘previous’ button to the page, along with this code, which seems to work. Have I got anything wrong?

$w.onReady(function () {

    //Set dataset and buttons into constants for ease of reference
    const storiesDataset = $w("#storiesData");
    const nextButton = $w("#nextButton");
    const prevButton = $w("#prevButton");

    //This function checks for next / previous pages and enables or disables the corresponding buttons
    function setButtons() {
        storiesDataset.hasNextPage() ? nextButton.enable() : nextButton.disable();
        storiesDataset.hasPreviousPage() ? prevButton.enable() : prevButton.disable();
    }

    //This function gets the next page and then updates the buttons
    function goToNextPage() {
        storiesDataset.nextPage();
        setButtons();
    }
    
    //This function gets the previous page and then updates the buttons
    function goToPreviousPage() {
        storiesDataset.previousPage();
        setButtons();
    }
    //Once the dataset is ready...
    storiesDataset.onReady( () => {
        //... we set the initial button states
        setButtons();
        //... and prepare to accept clicks on those buttons
        nextButton.onClick((event) => goToNextPage())
        prevButton.onClick((event) => goToPreviousPage())

    })

});

A small correction: since .nextPage() and .previousPage() are promises, you should wait for them to get resolved before you set the new button disable-enable state.
Something like:

function goToNextPage() {
        storiesDataset.nextPage()
	.then(setButtons);
    }
    
    //This function gets the previous page and then updates the buttons
    function goToPreviousPage() {
        storiesDataset.previousPage()
        .then(setButtons);
    }

Thanks, J.D.!

1 Like