paparonnie
paparonnie

Reputation: 170

How to make sure my value doesn't go below 0 in react?

I want to stop countCostMinus from giving me a value below 0, but it still is. For example, when I click 2 minor tickets, it gives me a value of 20 (0 + (2 * 10) = 20) but when I minus it by 1, its still recognising it as (0 - (1 * 10) = -10). I've tried to make it so that if the overallCost value goes below 0, it will just set the value to 0 but it isn't working. How do I achieve what I'm going for here? By the way, these are just 2 parts of a greater React function.

const countCostAdd = () => {
        let overallCost = (adultTickets.length * 25) + (minorTickets.length * 10);
        setCost(overallCost);
    };

    const countCostMinus = () => {
        let overallCost = (adultTickets.length * 25) - (minorTickets.length * 10);
        if(overallCost < 0) {
            overallCost == 0;
            setCost(overallCost)
        }else{
            setCost(overallCost);
        } 
    };

Upvotes: 0

Views: 392

Answers (1)

Shadi Amr
Shadi Amr

Reputation: 510

you need only this i hope:

const countCostMinus = () => {
        const overallCost = (adultTickets.length * 25) - (minorTickets.length * 10);
        setCost(overallCost < 0 ? 0 : overallCost)
    };

Upvotes: 2

Related Questions