Home > Net >  Setting a simple variable from onChange in React
Setting a simple variable from onChange in React

Time:12-17

I am just experimenting with ReactJS and came to an issue. I just want to update a variable according to the value of BootstrapSwitchButton. After some time of debugging, I came to a conclusion that variable is updating as needed but is not being displayed inside react rendering part but shows updated value from a function. My code is:

  const [state, setState] = useState(false);
  let btnValue;
  
  function changeValue(value)
  {
    console.log("Value: "   value)
    btnValue = value;
    setState(value); 
    console.log("Button Value at function: "   btnValue)
  }
  return (
    <div className="App">
      <BootstrapSwitchButton checked={true} onlabel="On" offlabel="Off" width={100} onChange={changeValue}/>
    {console.log("Button Value: "   btnValue)}
    </div>
  );
}

I just want to know that what's happening here? Why react does not show updated value even if state changes?

CodePudding user response:

You should not use local variables in a component context since they are not covered by state lifecycle. React does not know of this variable and hence does not "track" it. Instead of btnValue, use your state, since then react will take care of any actions associated with changes in your component. You can read more about that in the react state and lifecycle page.

function changeValue(value)
  {
    console.log("Value: "   value)
    setState(value); 
    console.log("Button Value at function: "   value)
  }
return (
    <div className="App">
      <BootstrapSwitchButton checked={true} onlabel="On" offlabel="Off" width={100} onChange={changeValue}/>
    {console.log("Button Value: "   state)}
    </div>
  );
  • Related