Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

javascript - Updating useState without inserting another object

This is the full code of the component, I am so tired that I can't think much on how to solve this problem

import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';


function CnContent(props) {
    const getCart = JSON.parse(localStorage.getItem('cart'));
    const products = [
        {
            id: 0,
            imgsrc: process.env.PUBLIC_URL + '/assets/images/products/grocery-staples/pro_1.jpg',
            name: "O'range 500 ml Coconut Oil(Bottle)",
            quantity: "500 ml",
            offer_price: "? 116",
            real_price: "? 219",
            inCart: 1
        },

        {
            id: 1,
            imgsrc: process.env.PUBLIC_URL + '/assets/images/products/grocery-staples/pro_2.jpg',
            name: "Parachute 100% Pure Coconut Oil (Plastic Bottle)",
            quantity: "600 ml",
            offer_price: "? 210",
            real_price: "? 250",
            inCart: 1
        },

        {
            id: 2,
            imgsrc: process.env.PUBLIC_URL + '/assets/images/products/grocery-staples/pro_3.jpg',
            name: "Fortune Soya Chunks",
            quantity: "1 kg",
            offer_price: "? 126",
            real_price: "? 135",
            inCart: 1
        },
    ]
    const [cart, setCart] = useState(getCart);

    useEffect(() => {
        localStorage.setItem('cart', JSON.stringify(cart));
    }, [cart])
    function addToCart(pr) {
        let duplicate = cart.find((x) => x.id === pr.id)

        if (!duplicate) {
            setCart((prevState) => {
                return [...prevState, pr]
            });
        }
        else {
            setCart((prevState) => [...prevState, prevState[pr.id] = { inCart: prevState[pr.id].inCart + 1 }]); // This creates another object and sends to the array (cart), but I want to change the value of the specific product(cart[pr.id]).
        }
    }

    return (
        <>
            <div className='cn-table'>
                <div className='section-left'></div>
                <div className='section-right'>

                    {
                        products.map((pr, i) => {
                            return (
                                <div tabIndex='-1' className='products' key={i}>
                                    <div className="products__wrapper">
                                        <Link to='https://www.youtube.com' className='products__link'>
                                            <div className='products__img'>
                                                <img src={pr.imgsrc} alt={pr.name}></img>
                                            </div>
                                            <div className='products__name'>{pr.name}</div>
                                            <div className='products__quantity'>{pr.quantity}</div>
                                        </Link>
                                        <div className='products__details'>
                                            <div className='products__details__price'>
                                                <div className='products__details__price__offer'>{pr.offer_price}</div>
                                                <div className='products__details__price__real'>{pr.real_price}</div>
                                            </div>
                                            <div className='add-to-cart zero-products'>
                                                <button className='add-to-cart__remove' >-</button>
                                                <button className='add-to-cart__text active'>{pr.inCart}</button>
                                                <button className='add-to-cart__add' onClick={() => addToCart(pr)}>+</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )
                        })
                    }
                </div>
            </div>
        </>
    )
}

export { CnContent };

These are results of localStorage value, the problem is instead of changing the value of inCart of the specific object, it's creating a new object with property "inCart".

0: {id: 0, pr_category: "grocery-staples", imgsrc: "/assets/images/products/grocery-staples/pro_1.jpg",…}
1: {id: 1, pr_category: "grocery-staples", imgsrc: "/assets/images/products/grocery-staples/pro_2.jpg",…}
2: {inCart: 1} /*Instead of this new object I want to change the value in the upper objects*/

Any suggestions will be appreciated. Thank you !

EDIT: Changed the value of inCart from 0 to 1.

question from:https://stackoverflow.com/questions/65834809/updating-usestate-without-inserting-another-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to map over the cart and update only the product you want

setCart((prevState) => prevState.map(product=>{
   if (product.id === pr.id) {
    return {
      ...product,
      inCart: product.inCart + 1
    }
   }
   return product;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...