'Script won't execute within NextJS page?

Hoping someone could please provide me with some advice regarding a problem I've run into in NextJS?

I have some JavaScript code that works properly within a plain html file, but for whatever reason won't work properly in NextJS.

As you can see in the screenshot, it gets stuck on Loading when it should pull in user info from an API.

My code inside my NextJS file looks like this:

import ArticleList from '../components/ArticleList'
import Script from 'next/script'

export default function Home({ articles }) {
    return (
    <div>

      <Head>
        <title>MFT Power BI - Next.js</title>
        <meta name='keywords' content='test,test,test'/>
       
      </Head>

    

<>
    <Script
      src="../components/scripts/reportSearch.js"
      strategy="beforeInteractive"
    />
   
  </>

      <div>
      <ArticleList articles={articles} />
    </div>

    </div>
    )
  }
  
 export const getStaticProps = async () => {
   const res = await fetch(`https://jsonplaceholder.typicode.com/posts?_limit=6`)
   const articles = await res.json()

   return {
     props: {
       articles,
     },
   }
 }

The code inside reportSearch.js is:

const result = document.getElementById('result')
const filter = document.getElementById('filter')
const listItems = []

getData()

filter.addEventListener('input', (e) => filterData(e.target.value))

async function getData() {
    const res = await fetch('https://randomuser.me/api?results=50')

    const { results } = await res.json()

    // Clear result
    result.innerHTML = ''

    results.forEach(user => {
        const li = document.createElement('li')

        listItems.push(li)

        li.innerHTML = `
            <img src="${user.picture.large}" alt="${user.name.first}">
            <div className={user-info}>
                <h4>${user.name.first} ${user.name.last}</h4>
                <p>${user.location.city}, ${user.location.country}</p>
                <p class="text-dark">${user.gender}</p>
            </div>
        `

        result.appendChild(li)
    })
}

function filterData(searchTerm) {
    listItems.forEach(item => {
        if(item.innerText.toLowerCase().includes(searchTerm.toLowerCase())) {
            item.classList.remove('hide')
        } else {
            item.classList.add('hide')
        }
    })
}

Any help with this would be greatly appreciated!



Sources

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

Source: Stack Overflow

Solution Source