Context changes not show

Viewed 36

A Simple cart context File:

import React, { useState } from "react";

const CartContext = React.createContext({
  showCart: () => {},
  hideCart: () => {},
  isCartVisible: false,
});

export const CartProvider = (props) => {
  const [cartStatus, setCartStatus] = useState(false);

  const handelShowCart = () => {
    setCartStatus(true);
  };

  const handelHideCart = () => {
    setCartStatus(false);
  };

  const value = {
    showCart: handelShowCart,
    hideCart: handelHideCart,
    isCartVisible: cartStatus,
  };

  return (
    <CartContext.Provider value={value}>{props.children}</CartContext.Provider>
  );
};

export default CartContext;

Implementing Cart context provide in APP js file.

import CartContext, { CartProvider } from "./Context/CartContext";

const App = () => {
  const ctx = useContext(CartContext);

  return (
    <CartProvider>
      {ctx.isCartVisible && <Cart />}
      <Header />
      <Meals />
    </CartProvider>
  );
};

using header cart button to open modal.

import React, { useContext } from "react";
import CartContext from "../Context/CartContext";

const HeaderCartBtn = () => {
  const ctx = useContext(CartContext);

  return (
    <button className={Styles["button"]} onClick={ctx.showCart}>
      <span className={Styles["icon"]}>
        <CartIcon />
      </span>
      <span>Your Cart</span>
      <span className={Styles["badge"]}>3</span>
    </button>
  );
};

export default HeaderCartBtn;

On clicking on Cart button on homepage, i can able to see console log. Code which i wrote to show the cart on click not working. Please suggest on this.

1 Answers

From the <App /> component, you are consuming data from the context, you need to wrap <App /> inside the provider as well so as to get the state value. You can put the provider in Index.js file:

<CartProvider>
  <App />
</CartProvider>

This way you can get updated ctx value correctly within <App /> component.

Related