S
S
SSSSTTTTAAAASSSS2022-01-06 12:14:57
JavaScript
SSSSTTTTAAAASSSS, 2022-01-06 12:14:57

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;

Given that the async function likesById(likes) sends unmodified likes to the server with the increment/decrement functions, but the initial state.

I tried to change the conditions when the button was pressed and send it by reference and not by a function - it did not give any effect.
I don't understand why setLikes doesn't work right away...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Scoo909010, 2022-01-06
@SSSSTTTTAAAASSSS

likesById needs to be called in useEffect because it's an asynchronous operation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question