function Setup() {
const [myBoolean, setMyBoolean] = useState(false);
useEffect(() => {
console.log(myBoolean);
}, [myBoolean]);
function HandleRadioClick() {
const radioButtons = document.getElementsByName("radio1");
for (let i = 0; i < radioButtons.length; i++) {
const radioButton = radioButtons[i] as HTMLInputElement;
if (radioButton.checked) {
const id = radioButton.id;
const option = id.substr(id.length - 7);
switch (option) {
case "Option1":
console.log("Pressed the first Radio Button");
// radioButtonOption1();
setMyBoolean(true);
console.log(myBoolean);
break;
case "Option2":
break;
case "Option3":
break;
default:
console.error("Unrecognized option:", option);
break;
}
}
}
}
const generate2 = () => {
HandleRadioClick();
const inputColor = hexValues.get(0);
const lightColorPalette = calculateLightColorPallette(inputColor);
const darkColorPalette = calculateDarkColorPallette(inputColor);
// setPalettes(lightColorPalette, darkColorPalette);
if (myBoolean) {
console.log("My Boolean is true");
console.log(darkColorPalette);
setPalettes({ light: lightColorPalette, dark: darkColorPalette });
} else {
console.log("My Boolean is false ");
setPalettes((prevPalettes) => ({ ...prevPalettes, light: lightColorPalette }));
}
};
return (
<div>
<button style={styles.button} onClick={generate2}>
Generate
</button>
</div>
);
}
How can I ensure that the boolean variable myBoolean is updated in time before the generate2 function is executed when the first radio button (Option1) is pressed, so that the condition based on myBoolean in the generate2 function works correctly? Currently, when I press the button, it calls the HandleRadioClick function, sets myBoolean to true inside the switch case, but when generate2 is executed, it doesn't seem to recognize the updated value of myBoolean, and the condition always behaves as if myBoolean is still false. What modifications should I make to fix this issue?
This is common mistake sometime developer do.
Answer: You are getting same value because working of useState
.
Because setState (2nd return agr of useState) work like : If you pass the value then the value will reflect in next re-render not in the same.
So please write logic according to that.
function Component(props){
const [state,setState] = useState({});
useEffect(()=>{
// run when state is updated
// run any function
},[state])
// on click event
function F1(){
// update the state
}
return (
<div>
<button onClick={F1}></button>
</div>
)
}