Home > OS >  Dynamically Change the button from Active to Inactive after removing or adding Items from the cart
Dynamically Change the button from Active to Inactive after removing or adding Items from the cart

Time:10-14

I have an "Add" button that is getting inactive immediately after pressing Add and changing the button title to "Added to Cart". Below is the logic (which is working well)

const [disabled, setDisabled] = useState(false);

<Button onPress={() => (props.addItemToCart(props.id), setDisabled(true))} disabled={disabled} title={!disabled ? "Add" : "Added to Cart"}/>

I want the button to be active again whenever the product removed from the cart. I have below which has items that are already in cart.

const cartProducts = props.cartSlice;
const itemExistsinCart = cartProducts.map((item, i) => item.product);

console.log(itemExistsinCart) output [sample products in the cart]

Array [
  "5f15d964e520d44421ed8e9c",
  "5f15d9b3e520d44421ed8e9d",
  "62e5285f92b4fde9dc8a384c",
]

What I want is to have the button active again only for the individual products if I remove the said products from the cart. Any ideas and suggestions on how to go about it are welcome. Thanks.

CodePudding user response:

I'm not seeing your entire code, but I suppose your cart and your product list are in different components, right?

So you need to control your application context, there are many ways to do that. I recommend you to take a look in React Context https://www.freecodecamp.org/news/react-context-for-beginners/

CodePudding user response:

If you have unique ids for every item. Use it to cross-check it in the cart. If you view the current item, create a function that checks the cart if the item is existing then the button will be disabled else if it isn't then enabled it.

  • Related