'React - Setting state inside use Effect problem
i ve got simple problem, just solving for 2 hours and cannot find solution(i am new to React)
I want to set State to true when all conditions inside use Effect are true. Use effect runs every time i click on button
const [allBtnOff, setAllBtnOff] = React.useState(false)
React.useEffect(() => {
if (btnOff.ER1 === true &&
btnOff.ER2 === true &&
btnOff.ER3 === true &&
btnOff.ER4 === true &&
btnOff.ER5 === true &&
btnOff.ER6 === true &&
btnOff.Dreier === true &&
btnOff.Vierer === true &&
btnOff.Full === true &&
btnOff.Kleine === true &&
btnOff.Grobe === true &&
btnOff.Kniffel === true &&
btnOff.Chance === true
)
{
setAllBtnOff(prevState => !prevState)
console.log(allBtnOff)
}
},[btnOff])
Problem is, that its always one step back so i have to click two times on button to set it true.
For more details:
I click a button and then it will set it true and will disable button. Same time use effect will run, so i need extra click button to check if conditions are true. Any solutions?
EDIT: (maybe understanding code more will help)
// BTN OFF/ON after passing score
const [btnOff, setBtnOff] = React.useState({
ER1: false,
ER2: false,
ER3: false,
ER4: false,
ER5: false,
ER6: false,
Dreier: false,
Vierer: false,
Full: false,
Kleine: false,
Grobe: false,
Kniffel: false,
Chance: false
})
// Passing score and disabling button
function handleClick(event) {
setTotalValues(prevState => {
return {
...prevState,
[event.target.name]: Score
}
})
setBtnOff(prevState => {
return {
...prevState,
[event.target.name]: true
}
})
}
return (
<div className="score--inside">
<h3>1ER:</h3>
<p>{totalValues.ER1}</p>
<button disabled={btnOff.ER1 && true} name="ER1" onClick={handleClick}>Add score</button>
</div>
// ...MULTIPLE SCORE--INSIDE BOXES
)
Solution 1:[1]
Create another useEffect and follow this:
React.useEffect(() => {
if (allBtnOff) console.log(allBtnOff)
},[allBtnOff])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vugar Taghiyev |
