开发者

How to Change the button text of Add to cart to Go to cart If the data from local Storage is available and how to set the has duplicate functionality

1.Below is my code in which I am storing my data if clicked on Add To Cart Button to Local Storage in an array object. But I don't want duplicate id's to store again if clicked again and if the id is stored once then change the text to Go To The Cart

2.This section shows how I set data to local Storage

  
   const [dta, setDta] = React.useState([]);
   const { data, cartVar } = props;

    React.useEffect(() => {
        setDta(JSON.parse(localStorage.getItem("variants")));
    }, []);

    const handleAddToCart = (e) => {
        e.preventDefault();
        let newUsers = {
            id: cartVar,
        };
        localStorage.setItem(
            "variants",
            JSON.stringify([...allusers, newUsers])
        );
        s开发者_如何转开发etAllusers(allusers.concat(newUsers));
    };

3.This Section Shows the Add To Cart Button


 

 <Button
                    style={{ width: "50%" }}
                    variant="contained"
                    onClick={handleAddToCart}
                >
                    {cartVar !== dta ? "Add TO CART" : "Go TO CART"}
                </Button>
  1. In local Stoge I am getting array of objects having repeatative duplicate id's. How to not set Duplicate id's


: 
{id: "UHJvZHVjdFZhcmlhbnQ6NjU="}
1
: 
{id: "UHJvZHVjdFZhcmlhbnQ6NjY="}
2
: 
{id: "UHJvZHVjdFZhcmlhbnQ6NjY="}
3
: 
{id: "UHJvZHVjdFZhcmlhbnQ6NjU="}
4
: 
{id: "UHJvZHVjdFZhcmlhbnQ6NjU="}
5
: 
{id: "UHJvZHVjdFZhcmlhbnQ6NjU="}
6
: 
{id: "UHJvZHVjdFZhcmlhbnQ6NjU="}
7
: 
{id: "UHJvZHVjdFZhcmlhbnQ6NjU="}
8
: 
{id: "UHJvZHVjdFZhcmlhbnQ6NjU="}
9
: 
{id: "UHJvZHVjdFZhcmlhbnQ6NjU="}
]


Add a condition to see if id exists

if(!dta.some(i => i.id === cartVar))
{
       let newUsers = {
            id: cartVar,
        };
        localStorage.setItem(
            "variants",
            JSON.stringify([...allusers, newUsers])
        );
        setAllusers(allusers.concat(newUsers));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜