Home > database >  React useState hook only updates once onClick
React useState hook only updates once onClick

Time:09-24

I am trying to toggle true/false in my component using useState but I've noticed it only toggles one time and does not go back and forth. On clicking the component, it toggles true but then it won't toggle back to false. Any ideas on how to solve?

const [sound, setSound] = useState(false);

return (
    <div>
    <ReactPlayer
         ...
         muted={sound}
         onClick={() => {
             setSound(!sound);
             console.log("on click", sound);
         }}
     />
     </div>
)

EDIT Thanks for the replies, I think the issue was the anon function, I solved it by doing this

         onClick={() => {
             setSound((sound) => !sound);
             console.log("on click", sound);
         }}

CodePudding user response:

import React, {useState} from 'react';
import './App.css';

const ReactPlayer = ({muted, onClick}: {muted: boolean, onClick: () => any}) => {
  return (
    <div>
      <button onClick={onClick}>Test</button>
      <p>{muted.toString()}</p>
    </div>
  )
}

function App() {
  const [sound, setSound] = useState(false);

  return (
    <div className="App">
        <ReactPlayer
        muted={sound}
        onClick={() => {
        setSound(!sound);
        console.log("on click", sound);
      }}
        />
    </div>
  );
}

export default App;

This code works perfectly, I don't know what you have in your ReactPlayer component, but this should work

CodePudding user response:

As of Chrome 66, videos must be muted in order to play automatically. Some players, like Facebook, cannot be unmuted until the user interacts with the video, so you may want to enable controls to allow users to unmute videos themselves. Please set muted={true}. see docs for more info

Check the live code here in sandbox link

import ReactPlayer from "react-player";
import React, { useState } from "react";

// Render a YouTube video player

export default function App() {
  const [play, setPlay] = useState(true);
  return (
    <div className="App">
      <ReactPlayer
        muted={play}
        url="https://www.youtube.com/watch?v=9DDX3US3kss"
      />
      Click to Mute or Unmute --
      <button style={{ margin: "15px" }} onClick={() => setPlay(!play)}>
        Mute/UnMute
      </button>
    </div>
  );
}
  • Related