Home > front end >  Clicking on the button handler doesnt effect immediately
Clicking on the button handler doesnt effect immediately

Time:10-24

Clicking on the button handler named handleDelivered immediately doesnt effect updatedQuantity. For example - by default quantity = 10 which is initial value of updatedQuantity, after clicking handleDelivered it should decrease value by 1 and should print on the console "updatedQuantity after delivered 9" but its showing

updatedQuantity after delivered 10 updatedQuantity before delivered 9

Code :

const { name, artist, img, description, price, quantity, supplier } = album;

    const [updatedQuantity, setupdatedQuantity] = useState(quantity);
    useEffect(() => {
        setupdatedQuantity(quantity)
    }, [quantity])
    console.log("updatedQuantity before delivered", updatedQuantity);


    const handleDelivered = () => {
        if (updatedQuantity > 0) {
            setupdatedQuantity(updatedQuantity - 1);
            console.log("updatedQuantity after delivered", updatedQuantity);
    }

CodePudding user response:

It would be better to use the previous value (prev) value in the set state.

    const { name, artist, img, description, price, quantity, supplier } = album;

    const [updatedQuantity, setupdatedQuantity] = useState(quantity);

    useEffect(() => {
        console.log("updatedQuantity after delivered", quantity);
    }, [quantity])

    const handleDelivered = () => {
        if (updatedQuantity > 0) {
            setupdatedQuantity(prev => prev - 1);
        }
    // ...
    }

The reason I suggest this is because having the setupdatedQuantity(prev => prev - 1); will grab the current value on updatedQuantity (say 10), and then set the state to be a new value (9).

The useEffect will catch this 10 -> 9 change of updatedQuantity as it is in the deps array, and console.log it out to you.

Here's the example from the docs

CodePudding user response:

Inside your handleDelivered, method updating the state of updatedQuantity will only update it in the next rerender. This is usually fast enough if you need it somewhere else in the code. However if you need it immediately in handleDelivered you should use the value you've calculated.

    const handleDelivered = () => {
        if (updatedQuantity > 0) {
            const newQuantity = updatedQuantity - 1
            setupdatedQuantity(newQuantity);
            console.log("updatedQuantity after delivered", newQuantity);
    }

CodePudding user response:

use the callback function in the setState to get the updated value

 setupdatedQuantity(newQuantity, () => {
   console.log("updatedQuantity after delivered", updatedQuantity);
 });
       
  • Related