Skip to content

useAddToCart

The useAddToCart hook allows you to add an item to the cart by interacting with the Centra Checkout API. This hook integrates seamlessly into your React application for handling shopping cart operations.

Overview

This hook interacts with the POST /items/{item} endpoint of the Centra Checkout API. It allows you to add an item to the current selection and automatically updates the state of the cart.

Parameters

  • options (optional): Mutation options provided to the underlying useMutation hook from React Query.
    • Example options include onSuccess, onError, and onSettled callbacks.

Returns

The hook returns an object from useMutation that contains:

  • mutate: A function to trigger the mutation.
  • data: The result of the mutation (updated selection).
  • isPending: A boolean indicating if the mutation is in progress.
  • error: An error object if the mutation fails.

Examples

Simple Usage

import { useAddToCart } from "@frend-digital/centra/client";
const AddToCartButton = ({ itemId }: { itemId: string }) => {
const { mutate, isPending, data, error } = useAddToCart();
const handleAddToCart = () => {
mutate({ itemId });
};
return (
<div>
<button onClick={handleAddToCart} disabled={isPending}>
{isPending ? "Adding..." : "Add to Cart"}
</button>
{error && <p>Error adding item: {error.message}</p>}
{data && <p>Item added to cart!</p>}
</div>
);
};

Advanced Usage

import { useAddToCart } from "@frend-digital/centra/client";
import { toast } from "your-toast-library";
const AddToCartWithFeedback = ({ itemId }: { itemId: string }) => {
const { mutate, isPending } = useAddToCart({
onSuccess: (data) => {
// Display a success toast
toast.success("Item added to cart!");
// Trigger additional UI updates if needed
console.log("Cart updated:", data);
},
onError: (error) => {
// Display an error toast
toast.error("Failed to add item to cart. Please try again.");
},
});
const handleAddToCart = () => {
mutate({ itemId });
};
return (
<div>
<button onClick={handleAddToCart} disabled={isPending}>
{isPending ? "Adding..." : "Add to Cart"}
</button>
</div>
);
};

API Interaction

Endpoint

POST /items/{item}

Request Parameters

  • Path Parameters:
    • item (string): The ID of the item to add.

Response

  • 200 OK: The updated selection.
  • 400 Bad Request: Invalid item ID.
  • 500 Internal Server Error: Server-side error.

Best Practices

  • Use the isPending state to provide feedback to users while the item is being added.
  • Handle errors gracefully by displaying user-friendly error messages.
  • Leverage onSuccess to trigger UI feedback like showing toasts or refreshing components.