# JavaScript API

Once the storefront script loads, `window.Wishlist` exposes a small API. Wait for `Wishlist.ready` before reading state. Ids are numeric strings; numbers and `gid://shopify/Product/<id>` strings are accepted as input too.

```js
window.Wishlist.ready.then(() => {
  console.log(Wishlist.count(), "saved products");
});
```

A TypeScript declaration file, `wishlist.d.ts`, describes the full API. Copy it into your theme or project to get types for `window.Wishlist` and the events.

## Methods

| Method | Returns | Description |
|---|---|---|
| `add({ productId, variantId?, listId?, quantity? })` | `Promise<boolean>` | Adds an item. Resolves `false` if a handler cancelled it or it failed. |
| `remove({ productId, variantId?, listId? })` | `Promise<boolean>` | Removes an item. Without `variantId`, removes every variant. Without `listId`, removes from every list the shopper owns. |
| `toggle({ productId, variantId?, listId? })` | `Promise<boolean>` | Resolves `true` when the item is now saved. |
| `has(productId, variantId?)` | `boolean` | Whether the product is saved. |
| `lists()` | `WishlistList[]` | The shopper's lists. |
| `items(listId?)` | `Promise<WishlistItem[]>` | Items of one list, or of every list the shopper owns. |
| `count()` | `number` | Number of distinct saved products. |
| `open({ listId? })` | `Promise<void>` | Opens the drawer or popup, or goes to the wishlist page. |
| `close()` | `void` | Closes the drawer or popup. |
| `on(event, handler)` | `() => void` | Subscribes to an event. Returns an unsubscribe function. |
| `off(event, handler)` | `void` | Unsubscribes. |

## Events

Events are available through `Wishlist.on()` and as DOM events on `document`. DOM events bubble and are `composed`, so they cross shadow roots.

| `Wishlist.on` | DOM event | Detail |
|---|---|---|
| `ready` | `wishlist:ready` | `{ version, productIds, count }` |
| `change` | `wishlist:change` | `{ version, productIds, count }` |
| `add` | `wishlist:add` | `{ productId, variantId?, listId? }` |
| `remove` | `wishlist:remove` | `{ productId, variantId?, listId? }` |
| `addToCart` | `wishlist:add-to-cart` | `{ items: [{ productId, variantId, quantity }], listId?, source }` |

```js
document.addEventListener("wishlist:add", (event) => {
  console.log("Saved", event.detail.productId);
});

Wishlist.on("change", ({ count }) => {
  document.querySelector(".my-count").textContent = count;
});
```

A `ready` handler registered after the script is ready runs at once.

Each add is also published to Shopify custom pixels and Google Tag Manager. See [Ad and analytics pixels](https://wishlist.themivo.com/docs/ad-pixels).

## Changing or cancelling an add

`beforeAdd` handlers run before every add. They can edit `event.detail` or cancel the add.

```js
Wishlist.on("beforeAdd", (event) => {
  if (event.detail.productId === "123") event.preventDefault();
});
```

## Changing Add to cart

The **Add to cart**, **Add all to cart** and **Move to cart** buttons in the wishlist add items with Shopify's `/cart/add.js`, then update your theme's cart icon. `beforeAddToCart` handlers run first and can change that.

`event.detail` holds `items` (`{ productId, variantId, quantity }`, one per line), `listId` and `source` (`drawer` or `page`; the popup counts as `drawer`).

**Edit the lines.** Change quantities or remove lines from `event.detail.items`. With no lines left, nothing is added.

```js
Wishlist.on("beforeAddToCart", (event) => {
  event.detail.items = event.detail.items.filter((line) => line.productId !== "123");
});
```

**Use your own cart.** Pass a promise to `event.respondWith()` to add the items your way, for example through a cart drawer app or your headless cart. The wishlist waits for it, then shows its "Added to cart" message and records the add in analytics. If the promise rejects, the wishlist shows the error's message. Give each line the property `_wl` with the value `list`, as the wishlist does with `/cart/add.js`, so its order counts as wishlist revenue (see [How revenue is counted](https://wishlist.themivo.com/docs/analytics#how-revenue-is-counted)).

```js
Wishlist.on("beforeAddToCart", (event) => {
  event.respondWith(
    myCart.add(event.detail.items.map((line) => ({ id: line.variantId, quantity: line.quantity }))),
  );
});
```

Call `respondWith()` and `preventDefault()` straight away in the handler, not after an `await`.

**Do everything yourself.** `event.preventDefault()` stops the add completely: nothing goes to the cart, and the wishlist shows no message and keeps the items in Save for later.

**Move to cart from Save for later.** The wishlist takes the items out of Save for later before your handler runs, so two clicks or two tabs can't add the same item twice: an item another click already moved isn't in `event.detail.items`. Items that don't reach the cart, because the add failed or a handler cancelled or dropped them, go back to Save for later as newly saved items.

**React after the add.** `addToCart` runs once the items are in the cart, for example to open your theme's cart drawer:

```js
document.addEventListener("wishlist:add-to-cart", () => {
  Wishlist.close();
  document.querySelector("cart-drawer")?.open();
});
```

## Debug mode

Add `?wl_debug=1` to any storefront URL to log state changes, requests and events to the browser console. The flag is remembered in this browser until you open a URL with `?wl_debug=0`.
