The useCheckoutAction hook enables interactions with checkout actions in a type-safe manner, automatically updating the checkout session upon successful execution.
Action Types
The hook supports various action types including:
ADD_ITEMS - Add items to the cart
REMOVE_ITEMS - Remove items from the cart
UPDATE_COUPONS - Update coupon codes
UPDATE_CUSTOMER_DETAILS - Update customer information
UPDATE_ITEMS_QUANTITY - Update quantities of items in the cart
UPDATE_SHIPPING_PACKAGES - Update shipping packages
UPDATE_SHIPPING_ADDRESSES - Update shipping addresses
UPDATE_PAYMENT_METHODS - Update payment methods
CREATE_ORDER - Create a new order
REQUEST - Make custom API requests to the backend
Parameters
actionType: ActionType - The type of checkout action to perform (e.g., ADD_ITEMS, REMOVE_ITEMS, etc.)
callback?: object - Optional configuration callbacks
onSuccess?: (data?: CheckoutSession) => void - Called when action succeeds
onError?: ({ serverError, validationErrors }) => void - Called when action fails
Return Value
Returns an object with:
execute: (input: Input) => void - Function to dispatch the action with the appropriate payload
executeAsync: (input: Input) => Promise<Result | undefined> - Async version of execute that returns a Promise with the action result
isPending: boolean - Boolean indicating if the action is currently processing
error?: object - Error information if the action failed
serverError?: ServerError - Error returned by the server
validationErrors?: ValidatorErrors<Input> - Input Validation errors
Each action type expects specific input parameters. Below are the details for each:
Navigate the tabs to see details of each action
ADD_ITEMS
type CartItemInput = {
id: string; // Id of the item on cartItems array inside the session
quantity: number; // Quantity to add
sellerId?: string; // Optional seller ID
};
// Usage
execute([{ id: "product123", quantity: 2 }]);
REMOVE_ITEMS
type RemoveItemsInput = number[]; // Array of item indexes to remove
// Usage
execute([0, 2]); // Removes first and third items
UPDATE_COUPONS
type CouponsInput = string[]; // Array of coupon codes
// Usage
execute(["SUMMER10", "FREESHIP"]);
UPDATE_CUSTOMER_DETAILS
type CustomerDetailsInput = {
email?: string;
firstName?: string;
lastName?: string;
phone?: string;
// Other customer fields
};
// Usage
execute({
email: "customer@example.com",
firstName: "John",
lastName: "Doe"
});
UPDATE_ITEMS_QUANTITY
type UpdateQuantityInput = {
index: number; // Item index in the cart
quantity: number; // New quantity
}[];
// Usage
execute([
{ index: 0, quantity: 3 },
{ index: 1, quantity: 1 }
]);
UPDATE_SHIPPING_PACKAGES
type ShippingPackageInput = {
id: string; // Package ID
items: number[]; // Array of item indexes
addressId?: string; // Optional shipping address ID
selectedTimeSlotId?: string; // Optional time slot ID for delivery
};
// Usage
execute([
{
id: "standard-delivery",
items: [0, 1, 2],
addressId: "home-address"
}
]);
UPDATE_SHIPPING_ADDRESSES
type ShippingAddressInput = {
postalCode: string; // Required
country: string; // Required
street?: string;
number?: string;
city?: string;
state?: string;
complement?: string;
neighborhood?: string;
receiverName?: string;
};
// Usage
execute([
{
postalCode: "12345",
country: "US",
street: "Main St",
number: "123",
city: "New York",
state: "NY"
}
]);
UPDATE_PAYMENT_METHODS
type PaymentMethodInput = {
methodId: string; // Payment method ID
referenceValue: number; // Payment amount
installments?: number; // Optional installments count
};
// Usage
execute([
{
methodId: "credit-card",
referenceValue: 99.99,
installments: 3
}
]);
CREATE_ORDER
type CreateOrderInput = {
isGuest?: boolean; // Whether to create a guest order
captchaToken?: string; // Optional captcha token for validation
};
// Usage
execute({
isGuest: true
});
REQUEST
Makes custom API requests to the backend. Unlike other actions, this action does not automatically update the checkout session.type RequestActionInput = {
url: string; // The API endpoint URL
method?: string; // HTTP method (GET, POST, etc.). Defaults to GET
headers?: Record<string, string>; // Optional custom headers
body?: string; // Optional request body (for POST/PUT requests)
revalidate?: boolean; // If true, revalidates the checkout session after request
};
// Usage - GET request
execute({
url: "https://example.com/api/custom-endpoint"
});
// Usage - POST request with body
execute({
url: "https://example.com/api/custom-endpoint",
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key: "value" }),
revalidate: true
});
Use the revalidate option to refresh the session after making changes.
Example
Import
import { useCheckoutAction } from '@ollie-shop/sdk';
Usage
const { execute, executeAsync, isPending, error } = useCheckoutAction(
actionType,
{
onSuccess: (data) => {
// Handle success
},
onError: ({ serverError, validationErrors }) => {
// Handle errors
}
}
);
// Execute the action (fire and forget)
execute({
// Input specific to the action type
});
// Or use executeAsync to await the result
const result = await executeAsync({
// Input specific to the action type
});
Action
import { useCheckoutAction } from '@ollie-shop/sdk';
function AddToCartButton({ productId, quantity }) {
const { execute, isPending } = useCheckoutAction('ADD_ITEMS', {
onSuccess: () => {
console.log('Item added successfully');
},
onError: ({ serverError }) => {
console.error('Failed to add item', serverError?.message);
}
});
return (
<button
onClick={() => execute({ items: [{ id: productId, quantity }] })}
disabled={isPending}
>
{isPending ? 'Adding...' : 'Add to Cart'}
</button>
);
}
Using executeAsync
import { useCheckoutAction } from '@ollie-shop/sdk';
function AddToCartButton({ productId, quantity }) {
const { executeAsync, isPending } = useCheckoutAction('ADD_ITEMS');
const handleAddToCart = async () => {
const result = await executeAsync({ items: [{ id: productId, quantity }] });
if (result?.data) {
console.log('Item added successfully', result.data);
}
};
return (
<button onClick={handleAddToCart} disabled={isPending}>
{isPending ? 'Adding...' : 'Add to Cart'}
</button>
);
}