useCoupon
Apply or remove a cart coupon through the Salla SDK, with loading and error state.
Use useCoupon to build a coupon box on your cart page: an input that applies a code, and a button that removes it.
Example
import { useState } from 'react';
import { useCoupon } from '@salla.sa/twilight-theme-engine/hooks/useCoupon';
export function CouponBox({ applied }: { applied?: string | null }) {
const { apply, remove, loading, error } = useCoupon();
const [code, setCode] = useState('');
if (applied) {
return (
<div>
<span>Coupon: {applied}</span>
<button onClick={remove} disabled={loading}>Remove</button>
</div>
);
}
return (
<div>
<input value={code} onChange={(e) => setCode(e.target.value)} />
<button onClick={() => apply(code)} disabled={loading}>Apply</button>
{error && <p role="alert">{error}</p>}
</div>
);
}Pass the applied code from the cart: cart.coupon. See Cart data.
API
function useCoupon(): UseCouponResult;
interface UseCouponResult {
value: string | null;
loading: boolean;
error: string | null;
apply: (code: string) => Promise<boolean>;
remove: () => Promise<boolean>;
}| Prop | Type | Description |
|---|---|---|
value | string | null | The code this hook applied, or null. |
loading | boolean | true while apply or remove runs. |
error | string | null | The message of the last failure, or null. |
apply | (code: string) => Promise<boolean> | Trims the code and adds it to the cart with salla.cart.addCoupon. Resolves true on success, false on failure. |
remove | () => Promise<boolean> | Removes the coupon with salla.cart.deleteCoupon. Resolves true on success, false on failure. |
Gotchas
- The hook changes the cart through the Salla SDK, and the cart is updated on the server. The hook does not refetch your cart data: read the new totals and
cart.couponfrom the cart, see Cart data. valueis local state and starts asnullon every page load, even when the cart already has a coupon. Read the applied code fromcart.coupon, not fromvalue.- An empty or blank code fails with the error
Please enter a coupon code(English only) and sends no request. - Server errors (an invalid or expired code) arrive in
erroras themessageof the error the SDK raised. applyandremovenever throw. Check the boolean they resolve.- Call them from event handlers, not during render: the hook is client-only, and it does nothing when the Salla SDK is not loaded yet.
- Store setting
settings.cart.apply_coupon_enabledsays whether the coupon box should be shown, see Store data.
Next
- Cart data:
cart.coupon, totals and discounts. useAsyncFn, the loading and error helper this hook is built on.- Cart page