I have 2 check boxes with state variables "isApproved, setIsApproved" and "isPlayer, setIsPlayer"
After both of these values are assigned, I need to perform some operation say getDetails(isApproved, isPlayer)
The way I know if these 2 state variables are set is by using useEffect()
useEffect(()=>{
getDetails(isApproved, isPlayer)
},[isApproved,isPlayer])
But the issue with this is, whenever user clicks on checkbox, one of these state variable value changes and again "getDetails" gets called
I want to call getDetails only for the first time after these 2 state variables are set
Any suggestions please?
CodePudding user response:
Use a ref to toggle when the action is called, and avoid calling the action if the ref is true
or nothing has changed from the initial values:
const initialIsApproved = false
const initialIsPlayer = false
const Demo = () => {
const [isApproved, setIsApproved] = useState(initialIsApproved)
const [isPlayer, setIsPlayer] = useState(initialIsPlayer)
const called = useRef(false)
useEffect(() => {
if(!called.current // would abort if the ref is true
&& isApproved !== initialIsApproved
&& isPlayer !== initialIsPlayer) {
called.current = true // set the ref to true
getDetails(isApproved, isPlayer)
}
}, [isApproved, isPlayer])
return (...)
}