import React, {useState, useEffect} from 'react';
const Test = ( {numar}) => {
const [likeStatus, setLikeStatus] = useState(true);
const [likeNumber, setLikeNumber] = useState(100);
const onLikeHandler = () => {
setLikeStatus(prevState => !prevState);
if(likeStatus){
setLikeNumber(prevState=> prevState 1)
} else {
setLikeNumber(prevState=>prevState-1);
}
}
console.log(likeStatus);
console.log(likeNumber);
return <button className={`like ${likeStatus ? 'liked' : ""}`} onClick={onLikeHandler}>{`Like | ${ likeNumber}`}</button>
}
export default Test;
I am trying to make a like button that likes/unlikes based on the click.
How can I make the second change state function wait for my first state function to finish? I tried using an use effect hook, and I am using the likeStatus in the dependecy array, but for some reason "the unlike" function triggers twice upon refresh"
CodePudding user response:
State update is async, and state is being accessed from closure which recreates only after rerender - meaning you can not set state and then in next line to expect that you will get that new state immediately, you will get new state but only in next function call(after element rerenders). Solution is to preserve new state in temp variable.
Rewrite to this:
const onLikeHandler = () => {
const newLikeStatus = !likeStatus; // Here you are preserving that new state in temp variable
setLikeStatus(newLikeStatus);
if(newLikeStatus){
setLikeNumber(prevState=> prevState 1)
} else {
setLikeNumber(prevState=>prevState-1);
}
}