joshwcomeau / use-sound

A React Hook for playing sound effects

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

soundEnabled doesn't change on boolean useState change

EthanBlockson opened this issue · comments

When I import this component into any other document, the boolean toggle works fine, but it doesn't affect soundEnabled. I have also tried name useState const as soundEnabled and passing it as { soundEnabled }.

The goal is to mute sounds onClick in the imported component.

export const useSoundPlayer = () => {
  // React states
  const [isSoundOn, setSounds] = useState(true); 
  const [hover, setHover] = useState(false);

  // Sound library
  const [playSound1] = useSound("/audio/VM_Button_Press.mp3", {
    soundEnabled: isSoundOn,
  });

  const [playSound2] = useSound("/audio/MoreTickets.mp3", {
    soundEnabled: isSoundOn,
  });

  // Turn sounds on/off
  const muteSounds = () => {
    setSounds(!isSoundOn);
    console.log(isSoundOn); // TEMP
  };

  // Change button style on hover
  const handleMouseEnter = () => {
    setHover(true);
    console.log(isSoundOn); // TEMP
  };

  const handleMouseLeave = () => {
    setHover(false);
  };

  return {
    playSound1,
    playSound2,
    soundPlayerButton: (
      <>
        <Image
          src={
            isSoundOn
              ? hover
                ? SoundOnIconWhite
                : SoundOnIconBlack
              : hover
              ? SoundOffIconWhite
              : SoundOffIconBlack
          }
          onClick={muteSounds}
          onMouseEnter={handleMouseEnter}
          onMouseLeave={handleMouseLeave}
          className={`settings-button ${hover ? "" : "off"}`}
          alt=""
        />
      </>
    ),
  };
};

export default useSoundPlayer;