Home > Software design >  Is changing the state this way direct?
Is changing the state this way direct?

Time:12-31

Is this correct?

    const {
        flavor, setFlavor,
        cart, setCart
    } = useContext(DataContext);
    
    function addProductToCart(pizza) {
        setCart(cart   1);
        flavor.push(pizza);
        setFlavor(flavor.filter(item => item));
    }

or should i do this?

    const {
        flavor, setFlavor,
        cart, setCart
    } = useContext(DataContext);
    
    function addProductToCart(pizza) {
        const copyFlavor = [...flavor];

        setCart(cart   1);
        copyFlavor.push(pizza);
        setFlavor(copyFlavor.filter(item => item));
    }

I know i shouldn't change the state directly, but i don't know if changing like that is directly or not.

CodePudding user response:

an easier and safer way to do it would be.

Although I do not understand the point of the filter you use. im guessing to generate a new array ?

const {
        flavor, setFlavor,
        cart, setCart
    } = useContext(DataContext);

function addProductToCart(pizza) {
    setCart(cart   1);
    setFlavor((flavors) => [...flavors, pizza]);
}
  • Related