Home > Enterprise >  React Context changes not showing
React Context changes not showing

Time:03-31

I have this component set up where I use the global context to keep track of my cart. However when the cartQty is updated I do not see the updated quantity on screen, only if I refresh the page.

const CartBody = () => {
  const { cart, setCart } = useGlobalContext();

  const increaseCartQty = (productName: any) => {
    const index = cart.findIndex((product) => product.name === productName);
    cart[index].quantity = cart[index].quantity   1;
    setCart(cart);
  };

 return (<div>{cart.quantity}</div>)
}

CodePudding user response:

You are mutating the state instead of creating a new one. When you set state in a function component, react does a === between the old state and the new state. If they're equal, it skips rendering.

Do this instead:

const increaseCartQty = (productName: any) => {
  const index = cart.findIndex((product) => product.name === productName);
  const newCart = [...cart];
  newCart[index] = {
    ...cart[index],
    quantity: cart[index].quantity   1,
  };
  setCart(newCart);
};

Or:

const increaseCartQty = (productName: any) => {
  const newCart = cart.map((product) => {
    return product.name === productName
      ? {
          ...product,
          quantity: product.quantity   1,
        }
      : product;
  });
  setCart(newCart);
};

  • Related