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

Is changing the state this way direct?

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.

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 :

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