NextJS Typescript Player

Encountering an issue during the build process, specifically with the error in audioRef.current.play(). The error message indicates that there is no play function available. I attempted to use an interface but it seems to not accept boolean values. Could this possibly be related to an issue with the Ref? Any assistance would be greatly appreciated.

import { useEffect, useRef, useState } from "react";
import styles from "./styles.module.scss";
import { IoPauseCircleSharp, IoPlayCircleSharp } from "react-icons/io5";

export default function Player() {
  const audioRef = useRef(null);

  const [isPlaying, setIsPlaying] = useState(false);

  function setPlayingState(state: boolean | ((prevState: boolean) => boolean)) {
    setIsPlaying(state);
  }

  function toggleIsPlaying() {
    setIsPlaying(!isPlaying);
  }

  useEffect(() => {
    if (!audioRef.current) {
      return;
    }

    if (isPlaying) {
      audioRef.current.play();
    } else {
      audioRef.current.pause();
    }
  }, [isPlaying]);

  return (
    <div>
      <div>
        {isPlaying ? (
          <button className={styles.pause} onClick={toggleIsPlaying}>
            <IoPauseCircleSharp className={styles.hero} />
          </button>
        ) : (
          <button className={styles.player} onClick={toggleIsPlaying}>
            <IoPlayCircleSharp className={styles.hero} />
          </button>
        )}
      </div>
      <audio
        src="https://player-ssl.kshost.com.br:12462/live"
        autoPlay={true}
        ref={audioRef}
        onPlay={() => setPlayingState(true)}
        onPause={() => setPlayingState(false)}
      />
    </div>
  );
}

Answer №1

Consider utilizing

let audioElement = useRef<HTMLAudioElement>(null);

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

Accessing URL fragments in Next JS with context during the execution of getServerSideProps

I am trying to extract a URL fragment using getServerSideProps. The URL is structured like this: http://localhost:3000/some-folder#desiredParam=value Even though I pass the context as an argument to the getServerSideProps function, I am struggling to retr ...

Mastering Interpolation in React with TypeScript is essential for creating dynamic and interactive UI components. By leveraging the

Incorporating and distributing CSS objects through ChakraUI presents a simple need. Given that everything is inline, it seems the main issue revolves around "& > div". However, one of the TypeScript (TS) errors highlights an unexpected flagging of ...

Leveraging the Apollo client cache in Next.js with getServerSideProps

Exploring the world of Next.js with Apollo Client has been quite an adventure for me. One challenge I am facing is establishing a smooth workflow between the server and client sides. In my SSR page, I execute a query within getServerSideProps and then tran ...

Error: Unable to access null properties while attempting to address Readonly property error by implementing an interface

Here is the code snippet I am working with: interface State { backgroundColor: boolean; isLoading: boolean; errorOccured: boolean; acknowledgment: string; } export class GoodIntention extends React.Component<Props, State> { ... onCli ...

Setting up ESM for Firebase functions: A step-by-step guide

Our server application needs to utilize the most recent ipfs-http-client as it is an authorized package for accessing IPFS. However, the project must switch to using ESM starting from v57.0.0. I have invested a significant amount of time into this and it h ...

Low scoring performance in Lighthouse on a nearly empty page built with Next.js

While working on my Next.js project locally, I used npm run dev for development. After testing my website, I noticed that it scored a 40 in Performance. https://i.stack.imgur.com/3jmro.png Despite trying to use Lighthouse in secret mode, the results rem ...

Webpack 4.1.1 -> The configuration.module contains a property 'loaders' that is unrecognized

After updating my webpack to version 4.1.1, I encountered an error when trying to run it: The configuration object is invalid. Webpack has been initialized with a configuration that does not match the API schema. - The 'loaders' property in ...

The useEffect function is repeatedly making API calls within a component, despite not having any dependencies specified

As a newcomer to React.Js, I'm encountering an issue with useEffect repeatedly calling an API without any specified Dependency. Is there another approach I should consider? The relevant file is located at: /pages/dashboard/speaking/[slug].js } else i ...

After triggering an action, I am eager to make a selection from the store

To accomplish my task, I must first select from the store and verify if there is no data available. If no data is found, I need to dispatch an action and then re-select from the store once again. Here is the code snippet that I am currently using: t ...

Is it possible to update the <Html "lang"/> attribute in next-i18next when the language changes in Next.js?

Next-i18next is being used for my multilingual website and it's working great for all components. However, I'm not sure how to change the language of the HTML tag in the _document.js file. Can anyone help me with this? ...

What causes the absence of CSS classes in production while utilizing Tailwind and next.js?

Tailwind version: v9.3.5 PostCSS Configuration: // postcss.config.js module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, ...(process.env.NODE_ENV === 'production' ? { '@fullhuman/p ...

Tips for maintaining the 'client use' code snippet at the beginning of your Vs Code script

In my quest to utilize the NextJs app directory, I've come across a dilemma. To implement client-side components, it mandates the usage of 'use client' at the beginning of the file. However, Vs Code has a tendency to relocate this statement ...

Determine the date and time based on the number of days passed

Hey there! I have a dataset structured like this: let events = { "KOTH Airship": ["EVERY 19:00"], "KOTH Castle": ["EVERY 20:00"], Totem: ["EVERY 17:00", "EVERY 23:00"], Jum ...

Adjust the main template according to the specific page in the Next.js 13 App Router

Within my Root Layout, I have a main navigation component that needs to display different headers such as 'Library' on one page and 'Configuration' on another. Is there a way to dynamically update the header of the main navigation compo ...

Sending properties in NextJS from the server side (Application routing)

In order to share data for each request, I have created an object with this data in the rootLayout. export interface IProps { children: React.ReactNode; data: any; } export default function RootLayout(props: IProps) { const {children} = props; ...

Tips on updating checkbox background color after being selected

I've been working on creating checkboxes for seat selection in Angular using a TypeScript file, but I'm facing an issue where the background color of the checkbox doesn't change after checking them. Here's my TypeScript function: gener ...

What is the best way to create a download package that won't cause the zip warning to pop up on browsers?

Users of my platform have the ability to access and download a variety of video editing templates that are bundled together in a zip file. Chrome is currently blocking these downloads for security reasons. Are there alternative methods for bundling the fi ...

Best practices for organizing and storing a todo list in ReactJS using local storage

import React, { useState, useEffect } from 'react'; const TodoList = () => { const [tasks, setTasks] = useState(JSON.parse(localStorage.getItem('tasks')) || []); const [newTask, setNewTask] = useState(''); con ...

Properties for a standard React component

Currently, I am developing a form component in react with typescript that requires a 'fieldStructures' and an 'onSubmit' prop. type FieldStructure { type: 'text'; name: string; label?: string; helpText?: string ...

Error encountered with Next.js and Square API: The Fetch API cannot load due to the unsupported URL scheme "webpack-internal"

I encountered an issue while attempting to retrieve stock data from the Square API. injectGlobalHook.js:1648 Fetch API cannot load webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ReactDevOverlay.js. URL scheme "webpack-internal ...