> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ollie.shop/llms.txt
> Use this file to discover all available pages before exploring further.

# useCheckoutAction

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
* `UPDATE_GIFT_CARDS` - Apply or update gift cards
* `UPDATE_CUSTOMER_PREFERENCES` - Update customer preferences (e.g. save data, locale)
* `SIMULATE_SESSION` - Simulate a checkout session without mutating the real one
* `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, input?: Input) => void` - Called when the action succeeds. Receives the updated session (or the order for `CREATE_ORDER`; `unknown` for `REQUEST`) and the input that was executed
  * `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

## **Input Parameters by Action Type**

Each action type expects specific input parameters. Below are the details for each:

<Warning>
  Navigate the tabs to see details of each action
</Warning>

<Tabs>
  <Tab title="ADD_ITEMS">
    ### **ADD\_ITEMS**

    ```typescript theme={"system"}
    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 }]);
    ```

    ###
  </Tab>

  <Tab title="REMOVE_ITEMS">
    ### **REMOVE\_ITEMS**

    ```typescript theme={"system"}
    type RemoveItemsInput = number[];  // Array of item indexes to remove

    // Usage
    execute([0, 2]);  // Removes first and third items
    ```

    ###
  </Tab>

  <Tab title="UPDATE_COUPONS">
    ### **UPDATE\_COUPONS**

    ```typescript theme={"system"}
    type CouponsInput = string[];  // Array of coupon codes

    // Usage
    execute(["SUMMER10", "FREESHIP"]);
    ```

    ###
  </Tab>

  <Tab title="UPDATE_CUSTOMER_DETAILS">
    ### **UPDATE\_CUSTOMER\_DETAILS**

    ```typescript theme={"system"}
    type CustomerDetailsInput = {
      email?: string;
      firstName?: string;
      lastName?: string;
      phone?: string;
      // Other customer fields
    };

    // Usage
    execute({
      email: "customer@example.com",
      firstName: "John",
      lastName: "Doe"
    });
    ```

    ###
  </Tab>

  <Tab title="UPDATE_ITEMS_QUANTITY">
    ### **UPDATE\_ITEMS\_QUANTITY**

    ```typescript theme={"system"}
    type UpdateQuantityInput = {
      index: number;    // Item index in the cart
      quantity: number; // New quantity
    }[];

    // Usage
    execute([
      { index: 0, quantity: 3 },
      { index: 1, quantity: 1 }
    ]);
    ```
  </Tab>

  <Tab title="UPDATE_SHIPPING_PACKAGES">
    ### **UPDATE\_SHIPPING\_PACKAGES**

    ```typescript theme={"system"}
    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" 
      }
    ]);
    ```

    ###
  </Tab>

  <Tab title="UPDATE_SHIPPING_ADDRESSES">
    ### **UPDATE\_SHIPPING\_ADDRESSES**

    ```typescript theme={"system"}
    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"
      }
    ]);
    ```

    ###
  </Tab>

  <Tab title="UPDATE_PAYMENT_METHODS">
    ### **UPDATE\_PAYMENT\_METHODS**

    ```typescript theme={"system"}
    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
      }
    ]);
    ```
  </Tab>

  <Tab title="CREATE_ORDER">
    ### **CREATE\_ORDER**

    ```typescript theme={"system"}
    type CreateOrderInput = {
      isGuest?: boolean;     // Whether to create a guest order
      captchaToken?: string; // Optional captcha token for validation
    };

    // Usage
    execute({
      isGuest: true
    });
    ```
  </Tab>

  <Tab title="REQUEST">
    ### **REQUEST**

    Makes custom API requests to the backend. Unlike other actions, this action does not automatically update the checkout session.

    ```typescript theme={"system"}
    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
    });
    ```

    <Note>
      Use the `revalidate` option to refresh the session after making changes.
    </Note>
  </Tab>
</Tabs>

## **Example**

### **Import**

```typescript theme={"system"}
import { useCheckoutAction } from '@ollie-shop/sdk';
```

### **Usage**

```typescript theme={"system"}
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

```typescript theme={"system"}
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([{ id: productId, quantity }])}
      disabled={isPending}
    >
      {isPending ? 'Adding...' : 'Add to Cart'}
    </button>
  );
}
```

### Using executeAsync

```typescript theme={"system"}
import { useCheckoutAction } from '@ollie-shop/sdk';

function AddToCartButton({ productId, quantity }) {
  const { executeAsync, isPending } = useCheckoutAction('ADD_ITEMS');

  const handleAddToCart = async () => {
    const result = await executeAsync([{ 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>
  );
}
```
