'Carousel randomly breaks and throws "Cannot read properties of undefined". Any suggestions on how to fix?

I'm trying to code my own portfolio website (I am new to this..), and I have 9 images that open their own modal using Javascript. Each of those modals has a carousel in them with 1-5 pictures each. The code I'm currently using works, but about 10% of the time, the button won't move to the next image, or it only moves between half of the images or the carousel breaks entirely, and the console displays

Uncaught TypeError: Cannot read properties of undefined (reading 'classList')
    at moveToNextSlide (main.js:121:22)
    at HTMLButtonElement.<anonymous> (main.js:63:66)

I've console logged the slides and next button each time you open a modal, and it shows a proper list of items, so it doesn't seem to have problems grabbing all the slide-items or the button, but sometimes it still breaks. Not sure what to do, or if I should just code the carousel entirely different.

My HTML sorta looks like

<dialog class="modal">
    <div class="modal-container">
        <div class="image-slide">

            <div class="slide-item slide-item-visible">
                <img src="" alt="">
            </div>

            <div class="slide-item">
                <img src="" alt="">
            </div>

            <div class="slide-actions">
                <button class="slide-next"></button>                                    

And Javascript

openPortfolioModal.forEach((grid, index) => grid.addEventListener("click", () => {

    modal[index].showModal()

    let slides = modal[index].querySelectorAll(".slide-item")

    let slideNext = modal[index].querySelector(".slide-next")
    slideNext.addEventListener("click", () => moveToNextSlide(slides))
}

function hideAllSlides(x) {
    for (let slide of x) {
        slide.classList.remove("slide-item-visible")
    }
}

let slidePosition = 0

function moveToNextSlide(x) {
    hideAllSlides(x)
    let totalSlides = x.length


    if (slidePosition === totalSlides - 1) {
        slidePosition = 0
    } else {
        slidePosition++
    }

    x[slidePosition].classList.add("slide-item-visible")
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source