An object in typescript has the potential to be undefined

Just starting out with Typescript and hitting a snag. Can't seem to resolve this error and struggling to find the right solution

useAudio.tsx

import { useEffect, useRef } from 'react';

type Options = {
  volume: number;
  playbackRate: number;
};

const useAudio = (src: string, { volume = 1, playbackRate = 1 }: Options) => {
  const sound = useRef(
    typeof Audio !== "undefined" ? new Audio(src) : undefined
    );

  useEffect(() => {
    if (Audio !== undefined) {
    sound.current.playbackRate = playbackRate;
    }
  }, [playbackRate]);
  useEffect(() => {
    sound.current.volume = volume;
  }, [volume]);

  return sound.current;
};

Answer №1

It seems that the error is arising from sount.current potentially being undefined, likely due to the condition

typeof Audio !== "undefined" ? new Audio(src) : undefined
. As a result, attempting to set undefined.playbackRate will not work as expected.

  useEffect(() => {
    if (Audio !== undefined) {
      if (sound.current) sound.current.playbackRate = playbackRate;
    }
  }, [playbackRate]);

  useEffect(() => {
    if (sound.current) sound.current.volume = volume;
  }, [volume]);

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

Using a PHP variable within a JavaScript function to incorporate its value into a select field, ultimately generating a response using JavaScript

As I work on developing a shopping cart, I have successfully stored the total value of the items in the cart in a PHP variable named $total. I attempted to transfer this value into a JavaScript variable labeled Shipping fee. Subsequently, I created a form ...

Node.JS encountered an issue preventing the variable from being saved

I've been attempting to store the request.headers, but every time it outputs as [object Object] in the txt file. var http = require("http"); url = require("url"); fs = require("fs"); var events = require('events'); var even = new events.Ev ...

Applying CDNJS CSS or external CSS to Nodemailer HTML templates with Jade and Express: A Guide

I am attempting to send emails using node mailer. I have a jade template with HTML markup in an external file, which is compiled and rendered correctly. However, the styles inserted through maxcdn or cdnjs are not being applied. In this situation, how can ...

Developing a HTML button through Javascript that triggers a method with a single parameter when clicked

My current project involves creating HTML buttons through JavaScript using AJAX. Each time I click one of these buttons, it triggers an AJAX function. If the AJAX request is successful, it retrieves a number that will be utilized in a for loop. As the loop ...

Tips for overlaying an image on a div regardless of its height

(!) Although this question may seem repetitive, I have not been able to find a suitable solution in any of the previous 10 topics. I apologize for the inconvenience and am actively seeking a resolution to this unique situation; Allow me to outline the iss ...

The Oracle Database listener is unaware of the service specified in the connect descriptor for node-oracledb

Having recently transitioned from on-premise databases using Oracle 11g to the Cloud where I needed to connect to Oracle 12c, I encountered an issue with my nodejs application. While it worked fine on-premises, in the cloud it threw the following error: e ...

AngularJS filters not functioning properly after applying additional filters

I have a page where I am filtering data based on multiple values. For each block in the list, I am using the following code snippet: data-ng-repeat="c in vm.competencies | filter : c.competencyTypeID = <number>" While some of the filters are workin ...

Why does trying to package a Windows app on OSX prompt a request for Wine installation?

For several months, I have been successfully utilizing Electron on macOS (10.11.6) to create and package both OSX and Windows applications. My current setup includes electron v1.7.3 and "electron-packager" "^8.5.2", all of which have not been updated in a ...

Looking to target an element using a cssSelector. What is the best way to achieve this?

Below are the CSS Selector codes I am using: driver.findElement(By.cssSelector("button[class='btn-link'][data-sugg-technik='append_numbers']")).click(); driver.findElement(By.cssSelector("button[class='btn-link'][data-sugg- ...

The Jquery .clone() function presents issues in Internet Explorer and Chrome browsers, failing to perform as expected

I need to duplicate an HTML control and then add it to another control. Here is the code I have written: ko.bindingHandlers.multiFileUpload = { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { va ...

Tips on expanding the background beyond the boundaries of a parent container with a specific width limit

Could you please take a look at the code snippet below? I am dealing with a situation where I have a container with a fixed width, and inside that container, there are rows whose width exceeds that of the parent container. Some of these rows have a backgro ...

Is there a way to toggle a single Reactstrap Collapse component?

Currently, I am working on a Next.JS application that displays a list of Github users. The goal is to have each user's information box toggle open and close when clicked, using Reactstrap's Collapse component. However, the issue I'm facing i ...

Canvas in the off state has been removed

My goal is to create a basic JavaScript library that includes rotating, translating, and scaling the canvas. One issue I am facing is when I rotate the canvas, half of the content ends up getting deleted because the center of rotation is set at (0, 0). I ...

Is it possible to execute functions inline with conditional logic in react?

Is there a way to shorten the long conditions inside an inline if-else statement in React by putting a function inside it? I attempted to do this but encountered an error stating that "discount is not defined." function getDiscount(props) { const d ...

Searching for image labels and substituting the path string

Upon each page load, I am faced with the task of implementing a script that scans through the entire page to identify all image src file paths (<img src="/RayRay/thisisianimage.png">) and then add a specific string onto the file paths so they appear ...

I'm experiencing a problem when trying to add a document to Firebase Firestore using React Native - it doesn't seem to

I'm currently working on a React Native project that utilizes Firebase v9. My goal is to add a user object to my user collection whenever a new user signs up through the sign-up screen. However, I've encountered an issue where the user object is ...

Vue is alerting me that I cannot assign a reactive property to an undefined, null, or primitive value, specifically null

When retrieving data from Firebase, I am attempting to update the properties of the object being displayed on the UI. However, whenever I try to make any changes to the data, an error is thrown. Error in v-on handler: "TypeError: Cannot use 'in&apos ...

Unexpected behavior observed with negated character: ? ^

I am looking to create a form where users can input their phone number and have the flexibility to choose how they want to separate the numbers. I have been using a regex pattern for validation: var regex = /[^0-9 \/-\\\(\)\+ ...

Console not displaying any logs following the occurrence of an onClick event

One interesting feature I have on my website is an HTML div that functions as a star rating system. Currently, I am experimenting with some JavaScript code to test its functionality. My goal is for the console to log 'hello' whenever I click on ...

Automatically numbering table columns with custom language localization in JavaScript using Jquery

Is there a method to automatically number table data in a local or custom language? As a Bengali individual, I have figured out how to automatically number the first data of each row using css and js. However, I am uncertain about how to implement custom n ...