Hi I am declaring an audio context like this and it says window in undefined. I tried declaring declare const window :any above window.Context but the error's still there. Anyone know how I can solve this?
window.AudioContext = window.AudioContext || (window as any).webkitAudioContext
export default function TestPage(){
const audioContext = new AudioContext();
return <>Hello</>
}
CodePudding user response:
next.js runs server side. window is only available on client side. So you will have to wait until component is mounted, like this:
export default function TestPage(){
const audioContext = useState(null);
useEffect(() => {
window.AudioContext = window.AudioContext || (window as any).webkitAudioContext;
audioContext.current = new AudioContext();
},[]);
return <>Hello</>
}
CodePudding user response:
It's because of the server side rendering, so when nextjs is being rendered on the server the window doesn't exist yet, because window is only on the client.
What I usually do is to have some sort of function that is triggered in the client to initialize window:
(I assume that you're using reactjs because of the component format and fragment on the snippet)
export default function TestPage() {
const [audioContext, setAudioContext] = useState<AudioContext | null>(null)
useEffect(() => {
if (typeof window !== 'undefined') {
const val = window.AudioContext = window.AudioContext || window.webkitAudioContext;
setAudioContext(val)
// or you can put your logic here without setting the state
}
}, [])
useCallback(() => {
if (audioContext !== null) {
const audioContext = new audioContext();
// your other logic for audio context
}
}, [audioContext ])
return <>Hello</>
}
