Answer the question
In order to leave comments, you need to log in
Why does the button work the second time?
I'm familiar with react-om and js. I'm trying to make a component - a counter.
But I don’t understand why it shows me the correct number of clicks, but after the update, the first click is always ignored.
Below code
import React, {useState} from 'react';
import classes from './LikeButton.module.css'
import DishesService from "../../API/DischesService.js";
const LikeButton = ({dish, changedLikes}) => {
const [likes, setLikes] = useState(dish)
function increment() {
setLikes({...likes, likes:likes.likes+1})
likesById(likes)
}
function decrement() {
setLikes({...likes, likes:likes.likes-1})
likesById(likes)
}
async function likesById(likes) {
await DishesService.likesByID(likes)
}
return (
<div>
<button
className={classes.likeButton}
onClick={() => {
increment()
changedLikes(likes)
}}
>
<img src={require('../../Images/Likes/like.png')} alt=''/>
</button>
<button
className={classes.likeButton}
onClick={() => {
decrement()
changedLikes(likes)
}}
>
<img src={require('../../Images/Likes/dislike.png')} alt=''/>
</button>
<p>{likes.likes}</p>
</div>
);
};
export default LikeButton;
Answer the question
In order to leave comments, you need to log in
likesById needs to be called in useEffect because it's an asynchronous operation.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question