Search code examples
javascriptreactjse-commerce

State do not update onClick in react


Yahya here

I am building Ecommerce App in react with the help of Strapi

This is my code:

// var is used because I want to use state in different functions

var [ functionIsRunning , setFunctionIsRunning] = useState(false);


const handleFavourite = () => {

    setFunctionIsRunning(true);
}

const navigateToSinglePage = () => {

    if(functionIsRunning=== false)

    {
        navigate("/product/" + id)
    }
}


return (
    <div className="product-card" onClick={navigateToSinglePage}>
        <div className="thumnail">
            <img src={process.env.REACT_APP_DEV_URL + data?.img?.data[0]?.attributes.url} alt="" />
            <div className="heart" onClick={handleFavourite}>
            <  AiOutlineHeart/>
            </div>
        </div>
        <div className="product-details">
            <span className="Name">{data?.Title}</span>
            <span className="price">Rs {data?.Price}</span>                
        </div>
    </div>
);

The states always remains false

I want add product in favourite without redirecting to Single Product page

If someone has another way to execute this process you can narrate

REGARDS!


Solution

  • You need to use useEffect hooks. Create a handle click function like this:

    handleClick = () => {
     #set your state variable to a new value here 
    } 
    

    Then use a use effect hook to perform an action when the state is changed like this:

    useEffect(() => {
      #navigate user to a different page here
    }, [<insert state variable to execute on here>]);
    

    The reason for this is that react components are meant to be pure, meaning they always have the same output for the same input. So any "side effects" that you want to occur on the change of a state, must occur inside a use effect hook, which will execute everytime the state is changed.