Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React how can I change a state based on a different state, in the same function

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);

    }


}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading