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

React Context changes not showing

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

>Solution :

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

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

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