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

Incorporating middleware to handle 404 errors in Express

scenario app.use("/api/tobaccos", tobaccos); app.use(function(err, req, res, next) { console.error(err.message); }); API details: router.get("/:id", async (req, res) => { console.log("GET TOBACCO:" + req.params.id); ...

Access the JSON data containing sub array values and showcase them on an HTML page by utilizing ngFor

Greetings! I am currently working on a web application where I need to showcase student data that is being received in JSON format. Below is the TypeScript code snippet that outlines the structure of the student data: export interface studentData{ ...

Ways to utilize/extract data from an enumeration

Hello there! I am currently diving into the world of React and Typescript, eager to expand my knowledge. Please bear with me if my explanations are not up to par. In my react app, I have a scenario where I created an enum that I want to utilize in two diff ...

How can a function be invoked in a child component from a parent component?

I am facing a challenge where I need to trigger the function showExtraBlogposts() in Blogpostreader.js upon clicking on a button rendered in Blog.js. Initially, I attempted to call it using onClick={Blogpostreader.showExtraBlogposts()} but it returned an ...

Tips for utilizing the "Sign In with Apple" feature through Apple JS

For implementing "Sign In with Apple" on a web platform using Apple JS, you can refer to the code example available at this link. Now, the query arises: where can I find the Client ID required for this process? I have tried using the app id identifier fro ...

Issues with parsing XML data when using the xml2js library

I am looking to extract and populate values from a large XML dataset into a mySQL table. The XML data structure is as follows: <BMS version="1.0"> <Summaries> <Summary Booking_strId="CWBL00D7CB8J8U" Booking_lngId="466244159" Trans_lngId="4 ...

What is the best way to display live data to multiple users with React and Firebase?

I'm working on a messaging app that needs to update in real-time. Currently, I have implemented the functionality to log in using Google, post messages, and display them on the screen. However, when another user logs in with a different Google account ...

An odd glitch occurring when transferring data from $_GET to $_SESSION

Currently, I am utilizing Opauth for user authentication on my website through Twitter and Facebook. Upon their departure from the site, I store a redirect URL in the session to ensure that they are redirected back to the exact page they were viewing prev ...

Ensure that the number is valid using Express Validator in Node.js

One thing that I've noticed when using express validator is the difference between these two code snippets: check('isActive', 'isActive should be either 0 or 1').optional({ checkFalsy : false, nullable : false }).isInt().isIn([0, 1 ...

loading the css and javascript files based on the specified prop parameter

In the process of working on a ReactJS file that utilizes the react-ace library, I currently have the following code implemented. import React, { Component } from 'react'; import 'brace/mode/html'; import 'brace/theme/monokai&apos ...

The value retrieved from redux appears to be varying within the component body compared to its representation in the return

Trying to fetch the most recent history value from the redux store to pass as a payload is presenting a challenge. When submitting a query, the history updates and displays the latest value within the map() function in return(), but when checking at // CON ...

Which costs more, using an undefined ng-bind or both ng-bind and ng-show together?

Assuming that toShowVar is undefined, which of these options would be more costly? <span ng-bind="toShowVar" ng-show="toShowVar"></span> or <span ng-bind="toShowVar"></span> The latter option would clearly not display anything o ...

Placing a hyperlink within template strings

Currently, I am working on implementing a stylish email template for when a user registers with their email. To achieve this, I am utilizing Express and Node Mailer. Initially, my code appeared as follows: "Hello, " + user.username + ",&bs ...

Error in syntax: An unexpected token was encountered during an AJAX request

I am currently working on a project that involves looping through multiple JSON files within a directory called "trips" and extracting data from each file to display on the front end of the website. However, I'm encountering a persistent error message ...

What is the goal of JSON.parse(JSON.stringify(x))?

During my recent project work, I stumbled upon the following code snippet: let newParams = JSON.parse(JSON.stringify(initialParams)); I'm curious - what exactly does this code achieve? ...

Tool for controlling the layout of the viewport with Javascript

I have experience using ExtJS in the past to create dashboards, and one of my favorite features is the full-screen viewport with a border layout. This allows for easy splitting of a dashboard into panels on different sides without creating excessive scroll ...

Having difficulty adding items to the shopping cart

While working on a simple checkout system using django and react, I encountered an issue. Upon clicking the add to cart button, instead of adding the item to the cart as intended, I receive a 404 page not found error. I suspect that the problem may lie in ...

Upon attempting to fetch input by name, Puppeteer reported the error message: 'Node is not clickable or not an HTMLElement'

This is the structure of my HTML: <div id="divImporte"> <p class="btn01"> <input type="button" name="Enviar Tasas" value="Enviar Tasas"> </p> </div> Here are the diffe ...

Is there a similar function in PHP to creating an array with a specified number of elements in JavaScript using "new Array(number)"?

While attempting to convert a basic Javascript function into PHP, I encountered a variable declared as var Variable = new Array (13). In PHP, variables are typically declared like this: $variable = array() But what does the "13" in new Array(13) signify? ...

Using JSON data to populate an HTML page

I'm currently working on a project that involves creating a "Twitter" page. The idea is to utilize the JSON file available at to display some of its content. However, I'm facing an issue where my page only shows the table headers and nothing els ...