Maxime Ghéraille
Maxime Ghéraille

Reputation: 1935

cannot change volume of audio with useRef

I am keep getting The left-hand side of an assignment expression may not be an optional property access error while wanting to change the volume of the htmlaudioelement

any idea on how to fix this ?

my code

  const [volume, setVolume] = useState<number>(50)
  const musicPlayers:HTMLAudioElement | undefined(
    typeof Audio !== "undefined"
      ? new Audio("")
      : undefined
  );

  useEffect(() => {
    musicPlayers.current?.volume = volume
  }, [volume]);

     <input
      type="range"
      className="w-full"
      value={volume}
      onChange={(e) => setVolume(e.target.value)}
    />

thanks

Upvotes: 0

Views: 794

Answers (1)

koralarts
koralarts

Reputation: 2112

The error is happening because you're attempting to assign a value to a property of an object that might be null or undefined.

Example:

musicPlayers.current?.volume = volume;

You can fix this by checking beforehand if the object exists.

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

Upvotes: 1

Related Questions