I know hooks are asynchronous and so I'll need to use useEffect()
hook along with dependency array param in order to grab the counter's value that's being updated in real time.
However, I need to use these values in the counter()
function and not in useEffect()
.
I can see the values being updated in useEffect()
correctly but how can I grab those updated values in real time in counter()
in order for me to use values?
I've tried (to no avail): Passing liked
and disliked
as params in the counter(liked, disliked)
function but that didn't help
const [liked, setLiked] = useState(0);
const [disliked, setDisliked] = useState(0);
useEffect(() => {
// Correct values are being logged
console.log("liked", liked);
console.log("disliked", disliked);
}, [liked, disliked]);
const counter = () => {
if(someCondition.........) {
setDisliked(disliked + 1);
handleLike();
} else {
setLiked(liked + 1);
handleDislike();
}
};
const handleLike = () => {
const url = 'http://127.0.0.1:8000/api/like';
const headers = {
"Accept": 'application/json'
};
let data = {
'liked' : liked // value updates on second click only
};
console.log(data);
axios.post(url, data, {headers})
.then(resp => {
console.log(resp.data);
}).catch(err => {
console.log(err);
});
};
const handleDislike = () => {
const url = 'http://127.0.0.1:8000/api/dislike';
const headers = {
"Accept": 'application/json'
};
let data = {
'disliked' : disliked // value updates on second click only
};
console.log(data);
axios.post(url, data, {headers})
.then(resp => {
console.log(resp.data);
}).catch(err => {
console.log(err);
});
};
return(
<button onClick={counter}>Click Here</button>
);