I'm trying to make a voting system like stackoverflow, when a user clicks a button to vote up / down, if he's not logged in, a pop-up modal is displayed. My user information is stored in context so I can use a hook to check if I have currently sign in user. The question is how can I properly make a check inside onClick handler.
My first suggestion was something like this.
function userVote(){
const [showModal, setShowModal] = useState();
const auth = useAuth();
const handleClick = () => !auth.user ? setShowModal(true) : "the logic for updating the user
vote if he is already signed in"
return (
<>
<button onClick={handleClick}></button>
{showModal ? <Modal /> : null}
</>
)
}
But as far as I know, it is not a good practice to make state updates inside conditions or I'm wrong. I suppose there is a better way of doing this.
if you want to get rid of the condition before updating the state modify your function to be like:
const handleClick = () => {
setShowModal(!auth.user)
if (auth.user) {
// Write the logics here
}
}
it sets the state no matter if auth.user exists or not.