The constructor for audio in Next JS cannot be found

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

Answer №1

Your implementation of useEffect is incorrect. Additionally, remember to provide a function for the onClick event. Consider updating your code as follows:

import { useState, useEffect } from 'react'

export default function Player({ url }) {

  const [audio, setAudio] = useState(null)

  useEffect(() => { setAudio(new Audio(url)) }, [])

  return <button onClick={() => { audio?.play() }}>Play Audio</button>
}

To learn more about Hooks, check out the Rules of Hooks

You can view this code in action on CodeSandbox

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`"Type is invalid" error occurring with component after importing it into a different project``

I am currently working on developing a custom Storybook 7 Typescript component library with React. I have successfully imported this library into another project using a private NPM package. However, one of the components in the library, specifically the ...

Unreachable prevState when utilizing the useState hook

I am currently working on a component where I need to capture the previousState of an element. However, no matter what I try, it keeps returning the initial value. This suggests that there is some re-rendering happening, causing it to constantly default to ...

When combining Socket.io 1.0 with express 4.2, the outcome is a lack of socket connection

According to the title, I am attempting to integrate socket.io 1.0.4 with express 4.2, but all requests with "/?EIO" are resulting in a 404 error. Below are my file configurations: ./bin/www : #!/usr/bin/env node var debug = require('debug')(& ...

Selecting Content Dynamically with jQuery

I have a webpage with multiple dynamic content sections. <div id="content-1"> <div id="subcontent-1"></div> <i id="delete-1"></i> </div> . . . <div id="content-10"> <div id="subcontent-10"></d ...

Spring Boot is having trouble identifying the JavaScript files

I've incorporated Spring Boot in my project and I'm working with a JSP file that looks like this: <%@ include file="common/header.jsp" %> <%@ include file="common/navigation.jsp" %> <div class="container"> ...

Having trouble getting NPM environment variables to function properly on a Windows system?

I have a confusion in my package.json file where I am attempting to compile less code using versioning. Here is an example of what I am trying to achieve: "scripts" { ... "build:css": "lessc --source-map css/index.less build/$npm_package_name.$npm_package ...

Retrieve the current time of day based on the user's timezone

Currently, I am working with a firebase cloud function that is responsible for sending push notifications to my app. My main requirement is to send notifications only during the day time. To achieve this, I have integrated moment-timezone library into my p ...

There seems to be an issue with the .html() function in one of my

I'm currently in the process of transitioning my code to Angular and I could use some assistance with creating a directive. Here's what I'm trying to convert: jQuery(document).ready(function ($) { "use strict"; $('#cool-naviga ...

"Using only JavaScript to target and manipulate child elements within the

I'm currently transitioning from using jQuery to pure JavaScript, and I've just started but am encountering difficulties. Specifically, I am unsure how to select child elements in the DOM. <div class="row-button"> <input type="submi ...

After creating my Docker container, it is unable to detect any new files within its assigned volume

I am encountering an issue with my Nextjs app and images in my docker-compose file on my Ubuntu VPM with bind volumes. After composing the website, I am unable to view any new files that are uploaded; only the ones that were in /root/docker/public at the t ...

AngularJS : "Executing successive promises" with additional functions interspersed

Recently, I encountered a challenge in my Angular project. As a newcomer to Angular, I was tasked with modifying a directive that handles forms to ensure the submit button is disabled during processing and then enabled again once all operations are complet ...

Want to achieve success with your AJAX calls in JavaScript? Consider using $.get

As I clean up my JavaScript code, I am looking to switch from using $.ajax to $.get with a success function. function getresults(){ var reqid = getUrlVars()["id"]; console.log(reqid); $.ajax({ type: "POST", url: "/api/ser/id/", ...

Exploring the asynchronous nature of componentDidMount and triggering a re-render with force

I am puzzled by the behavior in the code provided. The async componentDidMount method seems to run forceUpdate only after waiting for the funcLazyLoad promise to be resolved. Typically, I would expect forceUpdate to wait for promise resolution only when wr ...

Is there a way to provide a dynamic value for the p:remoteCommand ajax call?

My issue involves a p:dataTable that contains p:commandLink elements. I need to initiate an ajax call with parameters when the mouseover event occurs. After some research, it became clear that commandLink cannot trigger an ajax call on mouseover directly - ...

What is the best way to upload a file in Node.js using Express and Multer?

When attempting to send a file from the front end to my node js server, I encountered an issue with receiving the file on the back end. Here is the code snippet: <form id="file-upload-form" class="uploader" action="/uploa ...

Splitting a string in Typescript based on regex group that identifies digits from the end

Looking to separate a string in a specific format - text = "a bunch of words 22 minutes ago some additional text". Only interested in the portion before the digits, like "a bunch of words". The string may contain 'minute', & ...

What is the process for combining and compressing an Angular 2 application?

I am currently trying to concatenate and minify an angular2 application. My approach so far involved concatenating all my *.js files (boot.js, application.js then all components) into one file and injecting it into my index.html. I also removed the <s ...

Exploring keys rather than values in Vue application

Currently, I am facing an issue where I am retrieving the values for three keys from my API using Axios. However, each time I make a request, the values are being displayed four times for each key. After removing one key from my data models and retesting, ...

file_put_contents - store user-defined variables

When I execute this script, it successfully generates the html page as expected. However, I am encountering challenges in incorporating variables, such as the $_GET request. The content is enclosed in speech marks and sent to a new webpage on my site usin ...

Is it possible to use null and Infinity interchangeably in JavaScript?

I've declared a default options object with a max set to Infinity: let RANGE_DEFAULT_OPTIONS: any = { min: 0, max: Infinity }; console.log(RANGE_DEFAULT_OPTIONS); // {min: 0, max: null} Surprisingly, when the RANGE_DEFAULT_OPTIONS object is logged, i ...