I'm facing an issue and struggling to find a solution.
My project follows the standard structure of Next JS.
In the root directory, I have included a components
folder.
Within the components folder, there is a component with the following code:
import { useState } from 'react'
export default function Player({url}) {
const [audio, setAudio] = useState(new Audio(url))
return (
<button onClick={ audio.play() }>Play Audio</button>
)
}
This component (simplified for example) is imported into one of my pages.
The error that I am encountering is:
ReferenceError: Audio is not defined
I understand that this error occurs because the component is compiled on the server side and NodeJS doesn't recognize what Audio() is.
Despite this understanding, I haven't been able to find a working solution yet.
I attempted to import useEffect
and set the state within it after the component mounts, but this approach resulted in additional errors and doesn't seem to be the correct fix.
Any guidance regarding best practices for accessing browser APIs within NextJS components would be greatly appreciated.
**Update: A commenter requested the implementation using useEffect
import { useState, useEffect } from 'react'
export default function Player({url}) {
useEffect(() => {
const [audio, setAudio] = useState(new Audio(url))
}, [])
return (
<button onClick={ audio.play() }>Play Audio</button>
)
}
This results in
ReferenceError: audio is not defined