javascriptreactjscartreact-contextdispatch

React add to cart action


In my react project I have a seminarreg component that contains the information of each seminar. So I have fetched the corresponding API and get the items and rendered them. Also I have a Add to Cart link, so I defined the following function for it:

const { id } = useParams();
  const [item, setItem] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
   const [cartData, setCartData] = useState({
     titleEvent: null,
     dateEvent: null,
   });

  const url = "https://.../api/V1/homepage/events_english";

  useEffect(() => {
    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        const selectedItem = data.data.find((item) => item.id === Number(id));
        console.log(selectedItem);
        setItem(selectedItem);
        setIsLoading(false);
      })
      .catch((error) => console.log(error));
  }, []);

const handleLinkClick = () => {
    setCartData({
      titleEvent: item ? item.title_event : null,
      dateEvent: item ? item.date_event : null,
    });
  };

  const { dispatch } = useContext(CartContext);

catContext page is as follows:


// Define the initial state for the cart data
const initialCartData = {
  titleEvent: null,
  dateEvent: null,
};

// Define the reducer function
const cartReducer = (state, action) => {
  switch (action.type) {
    case "UPDATE_CART_DATA":
      return {
        ...state,
        titleEvent: action.payload.titleEvent,
        dateEvent: action.payload.dateEvent,
      };
    default:
      return state;
  }
};

// Create the cart context
const CartContext = createContext();

// Create a cart provider component using useReducer and the cartReducer
export const CartProvider = ({ children }) => {
  const [cartData, dispatch] = useReducer(cartReducer, initialCartData);

  return (
    <CartContext.Provider value={{ cartData, dispatch }}>
      {children}
    </CartContext.Provider>
  );
};

export default CartContext;

I've also import { CartProvider } from cartContext page and wrapped whole App in my index.js with . Finally cart component contains these:

export default function Cart() {
 const { cartData } = useContext(CartContext);

  return (
    <div>
      <Header className="twitter" />
      <Navbar />
      <div className="cart">
        <div className="cartH">Cart(2)</div>
        <div className="cartlist">
          <div className="cartlisttitle">
            <div>Date</div>
            <div>Item</div>
            <div>Description</div>
            <div>Price</div>
            <div>Delete</div>
          </div>
          <div>
            {cartData.titleEvent} {cartData.dateEvent}
          </div>
        </div>
      </div>
      <Footer />
    </div>
  );
}

Now not only when I clicked Add to Cart in seminarreg page nothing add to cart page, also the whole website disappears, starts loading and not stop.


Solution

  • I think the issue is that you are not dispatching the action to your reducer you are only setting it in your local state variable.

    In your handleClickLink function try dispatching that action instead of setting your local state variable something like this. Also you may need to move the definition of dispatch up above handleClickLink

    const handleLinkClick = () => {
        dispatch({type: 'UPDATE_CART_DATA', payload: {
          titleEvent: item ? item.title_event : null,
          dateEvent: item ? item.date_event : null,
        }})
      };