### Install Mantle React Package
Source: https://github.com/hey-mantle/react/blob/master/README.md
Install the Mantle react package using npm. This command should be run in your project's terminal.
```bash
npm install @heymantle/react
```
--------------------------------
### Add or Update Payment Method with useMantle
Source: https://context7.com/hey-mantle/react/llms.txt
Use `addPaymentMethod` to initiate the process of adding or updating a customer's payment details. This returns a SetupIntent URL for completing the payment setup.
```tsx
import { useMantle } from "@heymantle/react";
function PaymentMethodManager() {
const { addPaymentMethod, customer } = useMantle();
const handleAddPaymentMethod = async () => {
const result = await addPaymentMethod({
returnUrl: "https://myapp.com/settings/payment",
updateExistingPaymentMethods: true, // Update methods on existing subscriptions
});
if ("error" in result) {
alert(`Failed to add payment method: ${result.error}`);
return;
}
// Redirect to Stripe payment setup
if (result.url) {
window.open(result.url, "_top");
}
};
return (
Payment Methods
{customer?.paymentMethod ? (
Current: •••• {customer.paymentMethod.last4}
) : (
No payment method on file
)}
);
}
```
--------------------------------
### Initialize MantleProvider in React App
Source: https://github.com/hey-mantle/react/blob/master/README.md
Include the MantleProvider react context near the root of your component tree. Ensure you have your customer's Mantle API token available from a server-side identify request. This setup requires React, ReactDOM, and BrowserRouter.
```javascript
import { MantleProvider } from "@heymantle/react";
const App = (Component) => {
const [shop, setShop] = useState();
const fetchShop = async () => {
const response = await fetch('/api/shop');
setShop(await response.json());
}
useEffect(() => {
fetchShop();
}, [])
if (!shop) {
return ;
}
ReactDOM.render(
,
document.getElementById("app-container")
);
};
```
--------------------------------
### Format Subscription Plan Intervals
Source: https://context7.com/hey-mantle/react/llms.txt
Use these functions to get different string representations of subscription plan intervals. Ensure the plan object has an 'interval' property.
```tsx
import {
PlanInterval,
intervalLabel,
intervalLabelLong,
intervalLabelShort,
isRecommendedPlan,
customButtonLabel,
highestDiscount,
} from "@heymantle/react";
function PlanCard({ plan }) {
// Get interval labels
const shortInterval = intervalLabelShort(plan.interval);
// "mo" or "yr"
const longInterval = intervalLabelLong(plan.interval);
// "month" or "year"
const interval = intervalLabel({
interval: plan.interval,
useShortFormPlanIntervals: true,
});
// "mo" or "yr" based on useShortFormPlanIntervals
// Check if plan is recommended via custom fields
const recommended = isRecommendedPlan({
plan,
customFieldKey: "recommended", // looks for plan.customFields.recommended
});
// Get custom button label or default
const buttonText = customButtonLabel({
plan,
customFieldKey: "buttonLabel",
defaultLabel: "Subscribe",
});
// Get the best available discount
const discount = highestDiscount({ plan });
return (
{recommended && Most Popular}
{plan.name}
${plan.amount}/{shortInterval}
{discount && (
Save ${plan.amount - discount.discountedAmount} with code {discount.code}
)}
);
}
// Using PlanInterval enum
function IntervalToggle({ selectedInterval, onChange }) {
return (
);
}
```
--------------------------------
### Get Usage Report
Source: https://context7.com/hey-mantle/react/llms.txt
Retrieves a usage report for a specific usage metric over a given period.
```APIDOC
## GET /api/usage/report
### Description
Retrieves a usage report for a specific usage metric over a given period.
### Method
GET
### Endpoint
/api/usage/report
### Parameters
#### Query Parameters
- **usageId** (string) - Required - The ID of the usage metric.
- **period** (string) - Required - The period for the report (e.g., "current_billing_period", "last_30_days", "last_7_days").
### Response
#### Success Response (200)
- **report** (object) - The usage report.
- **totalUsage** (number) - The total usage for the metric.
- **limit** (number) - The usage limit.
- **remaining** (number) - The remaining usage.
#### Response Example
```json
{
"report": {
"totalUsage": 150,
"limit": 1000,
"remaining": 850
}
}
```
```
--------------------------------
### Use useMantle Hook for Data and Operations
Source: https://github.com/hey-mantle/react/blob/master/README.md
Utilize the useMantle hook within your components to access customer data, subscription information, available plans, and perform actions like subscribing or canceling subscriptions. This example also shows sending a custom usage event.
```javascript
import { useMantle } from "@heymantle/react";
const HomePage = () => {
const { customer, subscription, plans, subscribe, cancelSubscription, sendUsageEvent } = useMantle();
useEffect(() => {
sendUsageEvent({
eventName: 'page_view',
properties: {
path: window.location.href,
},
});
}, [window.location]);
return (
{customer.subscription ? (
You're currently susbcribed to: {customer.subscription.plan.name}
) : (
{plans.map((plan) => (
{plan.name}${plan.amount}
))}
)}
)
};
```
--------------------------------
### addPaymentMethod
Source: https://context7.com/hey-mantle/react/llms.txt
Initiates the process for a customer to add or update their payment method. This function returns a SetupIntent necessary for completing the payment method addition securely.
```APIDOC
## addPaymentMethod
### Description
Initiates the process of adding or updating a payment method for the customer. Returns a SetupIntent for completing the payment method addition.
### Method
`useMantle` hook
### Parameters
#### Function Parameters
- **returnUrl** (string) - Required - The URL to redirect the customer to after the payment method is added or updated.
- **updateExistingPaymentMethods** (boolean) - Optional - If `true`, existing payment methods associated with active subscriptions will be updated. Defaults to `false`.
### Returns
- **object**: An object containing either:
- **url** (string): The URL to redirect the customer to for payment setup (e.g., Stripe Checkout).
- **error** (string): An error message if the process failed.
### Request Example
```tsx
import { useMantle } from "@heymantle/react";
function PaymentMethodManager() {
const { addPaymentMethod, customer } = useMantle();
const handleAddPaymentMethod = async () => {
const result = await addPaymentMethod({
returnUrl: "https://myapp.com/settings/payment",
updateExistingPaymentMethods: true, // Update methods on existing subscriptions
});
if ("error" in result) {
alert(`Failed to add payment method: ${result.error}`);
return;
}
// Redirect to Stripe payment setup
if (result.url) {
window.open(result.url, "_top");
}
};
return (
Payment Methods
{customer?.paymentMethod ? (
Current: •••• {customer.paymentMethod.last4}
) : (
No payment method on file
)}
);
}
```
```
--------------------------------
### Initialize MantleProvider
Source: https://context7.com/hey-mantle/react/llms.txt
Set up the MantleProvider at the root of your React app to provide Mantle API access. Ensure you provide your Mantle appId, customerApiToken, and apiUrl. The `waitForCustomer` prop can be set to true to prevent rendering until customer data is fetched.
```tsx
import { MantleProvider } from "@heymantle/react";
function App() {
// customerApiToken is obtained from your server-side identify call
const customerApiToken = "cust_token_from_identify_endpoint";
return (
Loading...
}
throwOnError={false}
i18n={{
subscribe: "Get Started",
cancelSubscription: "Cancel Plan",
}}
>
);
}
```
--------------------------------
### Create Hosted Session with useMantle
Source: https://context7.com/hey-mantle/react/llms.txt
Use `createHostedSession` to open various HeyMantle flows like pricing pages or the billing portal. Configure the session type and options as needed.
```tsx
import { useMantle } from "@heymantle/react";
function HostedSessionExample() {
const { createHostedSession } = useMantle();
const openPricingPage = async () => {
const result = await createHostedSession({
type: "plans",
config: {
returnUrl: "https://myapp.com/settings",
showRecommendedBadge: true,
allowPlanChange: true,
},
});
if (!("error" in result) && result.url) {
window.open(result.url, "_blank");
}
};
const openBillingPortal = async () => {
const result = await createHostedSession({
type: "billing_portal",
config: {
returnUrl: window.location.href,
},
});
if (!("error" in result) && result.url) {
window.open(result.url, "_top");
}
};
return (
);
}
```
--------------------------------
### Manage Onboarding Checklists with React
Source: https://context7.com/hey-mantle/react/llms.txt
Use the `useMantle` hook to interact with checklist functions like `getChecklist`, `completeChecklistStep`, and `skipChecklistStep`. Load checklists on component mount and update the UI when steps are completed or skipped.
```tsx
import { useMantle } from "@heymantle/react";
import { useState, useEffect } from "react";
function OnboardingChecklist() {
const {
getChecklist,
getChecklists,
completeChecklistStep,
skipChecklistStep,
showChecklist
} = useMantle();
const [checklist, setChecklist] = useState(null);
useEffect(() => {
const loadChecklist = async () => {
// Get a specific checklist by handle
const result = await getChecklist("onboarding");
if (result && !("error" in result)) {
setChecklist(result);
}
// Or get multiple checklists
const allChecklists = await getChecklists(["onboarding", "advanced-setup"]);
// Mark checklist as shown to the user
await showChecklist({ idOrHandle: "onboarding" });
};
loadChecklist();
}, []);
const handleComplete = async (stepHandle: string) => {
await completeChecklistStep({
idOrHandle: "onboarding",
stepIdOrHandle: stepHandle,
});
// Refresh checklist
const updated = await getChecklist("onboarding");
setChecklist(updated);
};
const handleSkip = async (stepHandle: string) => {
await skipChecklistStep({
idOrHandle: "onboarding",
stepIdOrHandle: stepHandle,
});
const updated = await getChecklist("onboarding");
setChecklist(updated);
};
if (!checklist) return null;
return (
);
}
```
--------------------------------
### Manage Affiliate Program with React Hooks
Source: https://context7.com/hey-mantle/react/llms.txt
Use the useMantle hook to manage affiliate enrollment, track referrals, and display performance metrics within a React application. Ensure necessary data is loaded before rendering affiliate-specific components.
```tsx
import { useMantle } from "@heymantle/react";
import { useState, useEffect } from "react";
function AffiliatePortal() {
const {
getAffiliateProgram,
getAffiliate,
enrollAffiliate,
submitReferralRequest,
getAffiliateReferrals,
getAffiliateReferralRequests,
getAffiliateMetrics,
} = useMantle();
const [program, setProgram] = useState(null);
const [affiliate, setAffiliate] = useState(null);
const [metrics, setMetrics] = useState(null);
const [referrals, setReferrals] = useState([]);
useEffect(() => {
const loadAffiliateData = async () => {
const programData = await getAffiliateProgram();
if (!("error" in programData)) {
setProgram(programData);
}
const affiliateData = await getAffiliate();
if (affiliateData && !("error" in affiliateData)) {
setAffiliate(affiliateData);
// Load metrics and referrals for enrolled affiliates
const metricsData = await getAffiliateMetrics();
if (!("error" in metricsData)) setMetrics(metricsData);
const referralsData = await getAffiliateReferrals({
page: 0,
limit: 25,
sort: "createdAt",
sortDirection: "desc",
});
if (!("error" in referralsData)) setReferrals(referralsData.referrals);
}
};
loadAffiliateData();
}, []);
const handleEnroll = async () => {
const result = await enrollAffiliate({
name: "John Doe",
email: "john@example.com",
agreedToTerms: true,
});
if (!("error" in result)) {
setAffiliate(result);
}
};
const handleSubmitReferral = async (formData) => {
const result = await submitReferralRequest({
shopDomain: formData.shopDomain,
customerName: formData.customerName,
notes: formData.notes,
date: new Date().toISOString(),
});
if (!("error" in result)) {
alert("Referral submitted for review!");
}
};
if (!program) return
Loading affiliate program...
;
return (
Affiliate Program
Commission: {program.commissionPercent}%
{!affiliate ? (
) : (
Your Affiliate Dashboard
Referral Code: {affiliate.referralCode}
Referral Link: {affiliate.referralLink}
{metrics && (
Performance Metrics
Total Referrals: {metrics.totalReferrals}
Confirmed: {metrics.confirmedReferrals}
Pending: {metrics.pendingReferrals}
Total Earnings: ${metrics.totalEarnings}
)}
Your Referrals
{referrals.map((ref) => (
{ref.customerName}{ref.status}${ref.commission}
))}
)}
);
}
```
--------------------------------
### Calculate Responsive Grid Layouts
Source: https://context7.com/hey-mantle/react/llms.txt
Use `columnCount` and `columnSpan` to determine the optimal number of columns and responsive grid spans based on the number of items. These functions are useful for creating adaptive layouts.
```tsx
import { columnSpan, columnCount } from "@heymantle/react";
function PlanGrid({ plans }) {
const count = plans.length;
const columns = columnCount(count);
const spans = columnSpan(count);
// columnCount returns optimal column count:
// 4 items -> 4 columns
// 3 items -> 3 columns
// 2 items -> 2 columns
// 1 item -> 1 column
// columnSpan returns responsive spans for each breakpoint:
// 4 items -> { xs: 6, sm: 6, md: 2, lg: 3, xl: 3 }
// 3 items -> { xs: 6, sm: 6, md: 2, lg: 4, xl: 4 }
// 2 items -> { xs: 6, sm: 6, md: 3, lg: 6, xl: 6 }
// 1 item -> { xs: 6, sm: 6, md: 6, lg: 12, xl: 12 }
return (
{plans.map((plan) => (
))}
);
}
```
--------------------------------
### createHostedSession
Source: https://context7.com/hey-mantle/react/llms.txt
Creates a hosted session for various checkout and management flows, including plan selection, billing portal access, and custom configurations.
```APIDOC
## createHostedSession
### Description
Creates a hosted session for various checkout and management flows. Supports different session types for plans, billing portal, and custom configurations.
### Method
`useMantle` hook
### Parameters
#### Function Parameters
- **type** (string) - Required - The type of hosted session to create. Supported types include: `"plans"`, `"billing_portal"`, and custom types.
- **config** (object) - Required - Configuration options for the hosted session.
- **returnUrl** (string) - Required - The URL to redirect the customer to after the session is completed.
- **showRecommendedBadge** (boolean) - Optional - If `true`, displays a "Recommended" badge on plans.
- **allowPlanChange** (boolean) - Optional - If `true`, allows customers to change their subscription plan within the session.
- **...other configuration options** - Depending on the session `type`.
### Returns
- **object**: An object containing either:
- **url** (string): The URL for the hosted session if successful.
- **error** (string): An error message if the session creation failed.
### Request Example
```tsx
import { useMantle } from "@heymantle/react";
function HostedSessionExample() {
const { createHostedSession } = useMantle();
const openPricingPage = async () => {
const result = await createHostedSession({
type: "plans",
config: {
returnUrl: "https://myapp.com/settings",
showRecommendedBadge: true,
allowPlanChange: true,
},
});
if (!("error" in result) && result.url) {
window.open(result.url, "_blank");
}
};
const openBillingPortal = async () => {
const result = await createHostedSession({
type: "billing_portal",
config: {
returnUrl: window.location.href,
},
});
if (!("error" in result) && result.url) {
window.open(result.url, "_top");
}
};
return (
);
}
```
```
--------------------------------
### Subscribe Customer to Single or Multiple Plans
Source: https://context7.com/hey-mantle/react/llms.txt
Use the `subscribe` hook to enroll a customer in one or more plans. Supports hosted checkout flows with options for trial periods, discounts, and payment method preferences. Ensure `returnUrl` is set for redirecting after checkout.
```tsx
import { useMantle } from "@heymantle/react";
function PlanSelector() {
const { subscribe, plans } = useMantle();
const handleSubscribe = async (planId: string) => {
const subscription = await subscribe({
planId,
returnUrl: "https://myapp.com/subscription/success",
trialDays: 7,
discountId: "discount_abc123", // Optional discount
useSavedPaymentMethod: true,
// Stripe-specific options
hosted: true,
automaticTax: true,
requireBillingAddress: true,
prorationBehavior: "create_prorations",
});
if ("error" in subscription) {
console.error("Subscription failed:", subscription.error);
return;
}
// Redirect to Shopify/Stripe checkout
if (subscription.confirmationUrl) {
window.open(subscription.confirmationUrl, "_top");
}
};
// Subscribe to multiple plans at once
const handleMultiPlanSubscribe = async () => {
const result = await subscribe({
planIds: ["plan_base_123", "plan_addon_456"],
returnUrl: "https://myapp.com/subscription/success",
});
if (!("error" in result) && result.confirmationUrl) {
window.open(result.confirmationUrl, "_top");
}
};
return (
{plans.map((plan) => (
))}
);
}
```
--------------------------------
### Subscribe to Plans
Source: https://context7.com/hey-mantle/react/llms.txt
Subscribes a customer to one or more plans. Supports single plan subscription via `planId` or multiple plans via `planIds`. Returns a subscription object with a confirmation URL for hosted checkout flows.
```APIDOC
## POST /api/subscriptions
### Description
Subscribes a customer to one or more plans. Supports single plan subscription via `planId` or multiple plans via `planIds`. Returns a subscription object with a confirmation URL for hosted checkout flows.
### Method
POST
### Endpoint
/api/subscriptions
### Parameters
#### Request Body
- **planId** (string) - Optional - The ID of a single plan to subscribe to.
- **planIds** (array of strings) - Optional - An array of plan IDs to subscribe to.
- **returnUrl** (string) - Required - The URL to redirect to after successful subscription.
- **trialDays** (number) - Optional - The number of trial days to grant.
- **discountId** (string) - Optional - The ID of a discount to apply.
- **useSavedPaymentMethod** (boolean) - Optional - Whether to use a saved payment method.
- **hosted** (boolean) - Optional - Whether to use hosted checkout.
- **automaticTax** (boolean) - Optional - Whether to enable automatic tax calculation.
- **requireBillingAddress** (boolean) - Optional - Whether to require a billing address.
- **prorationBehavior** (string) - Optional - The proration behavior for the subscription.
### Request Example
```json
{
"planId": "plan_abc123",
"returnUrl": "https://myapp.com/subscription/success",
"trialDays": 7,
"discountId": "discount_abc123",
"useSavedPaymentMethod": true,
"hosted": true,
"automaticTax": true,
"requireBillingAddress": true,
"prorationBehavior": "create_prorations"
}
```
### Response
#### Success Response (200)
- **confirmationUrl** (string) - The URL for hosted checkout.
- **subscription** (object) - The subscription object.
#### Response Example
```json
{
"confirmationUrl": "https://checkout.stripe.com/pay/cs_test_..."
}
```
```
--------------------------------
### Create One-Time Charge with useMantle
Source: https://context7.com/hey-mantle/react/llms.txt
Use `createOneTimeCharge` to process one-time payments for add-ons or credits. Ensure to handle the result for errors and redirect to the confirmation URL.
```tsx
import { useMantle } from "@heymantle/react";
function PurchaseCredits() {
const { createOneTimeCharge } = useMantle();
const handlePurchase = async (amount: number, credits: number) => {
const result = await createOneTimeCharge({
amount,
name: `${credits} API Credits`,
currencyCode: "USD",
returnUrl: "https://myapp.com/purchase/success",
test: false, // Set to true for testing
});
if ("error" in result) {
alert(`Purchase failed: ${result.error}`);
return;
}
// Redirect to payment confirmation
if (result.confirmationUrl) {
window.open(result.confirmationUrl, "_top");
}
};
return (
Purchase Additional Credits
);
}
```
--------------------------------
### Customize Labels and Internationalization
Source: https://context7.com/hey-mantle/react/llms.txt
Wrap your application with MantleProvider and pass custom labels via the 'i18n' prop to override default UI strings. Ensure 'appId' and 'customerApiToken' are provided.
```tsx
import { MantleProvider, Labels } from "@heymantle/react";
// Default labels available
const defaultLabels = {
subscribe: "Subscribe",
cancelSubscription: "Cancel Subscription",
addPaymentMethod: "Add Payment Method",
CurrentPlan: "Current plan",
ChangePlan: "Change plan",
FreeTrialLength: "{{ trialDays }}-day free trial",
AmountPerInterval: "{{ amount }} per {{ interval }}",
// ... and more
};
// Customize labels for your app
function App() {
const customLabels = {
...Labels,
subscribe: "Get Started",
cancelSubscription: "End Membership",
CurrentPlan: "Your Plan",
MostPopular: "Best Value",
FreeTrialLength: "Try free for {{ trialDays }} days",
};
return (
);
}
// Access labels in components
function PlanDisplay() {
const { i18n, subscription } = useMantle();
return (
{i18n.CurrentPlan}
{subscription?.plan.name}
);
}
```
--------------------------------
### Format Monetary Amounts with React
Source: https://context7.com/hey-mantle/react/llms.txt
Use the money utility function from @heymantle/react to format currency values. It supports different currencies and options for displaying cents.
```tsx
import { money } from "@heymantle/react";
function PriceDisplay() {
const price = 99.99;
const annualPrice = 999;
return (
{/* Output: With cents: $100.00 */}
{/* Different currencies */}
EUR: {money(49.99, "EUR")}
{/* Output: EUR: €49.99 */}
GBP: {money(39.99, "GBP")}
{/* Output: GBP: £39.99 */}
);
}
```
--------------------------------
### createOneTimeCharge
Source: https://context7.com/hey-mantle/react/llms.txt
Creates a one-time charge for the customer. This is suitable for add-ons, credits, or one-time purchases that are not part of a recurring subscription.
```APIDOC
## createOneTimeCharge
### Description
Creates a one-time charge for the customer, useful for add-ons, credits, or one-time purchases outside of the subscription.
### Method
`useMantle` hook
### Parameters
#### Function Parameters
- **amount** (number) - Required - The monetary amount to charge.
- **name** (string) - Required - The name or description of the item being purchased.
- **currencyCode** (string) - Required - The ISO 4217 currency code (e.g., "USD", "EUR").
- **returnUrl** (string) - Required - The URL to redirect the customer to after the charge is completed or fails.
- **test** (boolean) - Optional - Set to `true` for testing purposes. Defaults to `false`.
### Returns
- **object**: An object containing either:
- **confirmationUrl** (string): The URL for payment confirmation if successful.
- **error** (string): An error message if the charge failed.
### Request Example
```tsx
import { useMantle } from "@heymantle/react";
function PurchaseCredits() {
const { createOneTimeCharge } = useMantle();
const handlePurchase = async (amount: number, credits: number) => {
const result = await createOneTimeCharge({
amount,
name: `${credits} API Credits`,
currencyCode: "USD",
returnUrl: "https://myapp.com/purchase/success",
test: false, // Set to true for testing
});
if ("error" in result) {
alert(`Purchase failed: ${result.error}`);
return;
}
// Redirect to payment confirmation
if (result.confirmationUrl) {
window.open(result.confirmationUrl, "_top");
}
};
return (
Purchase Additional Credits
);
}
```
```
--------------------------------
### Manage Notifications with React
Source: https://context7.com/hey-mantle/react/llms.txt
Utilize the `useMantle` hook for notification management, including `listNotifications`, `updateNotification`, `trackNotificationCta`, and `triggerNotificationCta`. Fetch notifications on component mount and handle user interactions like dismissing or clicking CTAs.
```tsx
import { useMantle } from "@heymantle/react";
import { useState, useEffect } from "react";
function NotificationCenter() {
const {
listNotifications,
updateNotification,
trackNotificationCta,
triggerNotificationCta
} = useMantle();
const [notifications, setNotifications] = useState([]);
useEffect(() => {
const loadNotifications = async () => {
const result = await listNotifications();
if (!("error" in result)) {
setNotifications(result.notifies);
}
};
loadNotifications();
}, []);
const handleDismiss = async (id: string) => {
await updateNotification({
id,
dismissedAt: new Date(),
});
setNotifications(notifications.filter((n) => n.id !== id));
};
const handleRead = async (id: string) => {
await updateNotification({
id,
readAt: new Date(),
});
};
const handleCtaClick = async (notification) => {
// Track the CTA interaction
await trackNotificationCta({ id: notification.id, type: "click" });
// Trigger the CTA action
await triggerNotificationCta({ id: notification.id });
// Navigate or perform action
if (notification.ctaUrl) {
window.open(notification.ctaUrl, "_blank");
}
};
return (
Notifications ({notifications.length})
{notifications.map((notification) => (
handleRead(notification.id)}>
{notification.title}
{notification.message}
{notification.ctaLabel && (
)}
))}
);
}
```
--------------------------------
### Use useMantle Hook for Subscription Management
Source: https://context7.com/hey-mantle/react/llms.txt
Access customer data, subscription status, available plans, and perform actions like subscribing or canceling within your components using the useMantle hook. This hook must be used within a MantleProvider context.
```tsx
import { useMantle } from "@heymantle/react";
function SubscriptionPage() {
const {
customer,
subscription,
plans,
loading,
subscribe,
cancelSubscription,
refetch,
} = useMantle();
if (loading) return
Loading...
;
return (
Welcome, {customer?.name}
{subscription ? (
Current Plan: {subscription.plan.name}
Status: {subscription.status}
) : (
Available Plans
{plans.map((plan) => (
{plan.name}
${plan.amount}/{plan.interval}
))}
)}
);
}
```
--------------------------------
### Retrieve Usage Report
Source: https://context7.com/hey-mantle/react/llms.txt
Use `getUsageReport` to fetch a customer's usage data for a specific metric over a defined period. The report includes total usage, limits, and remaining usage.
```tsx
import { useMantle } from "@heymantle/react";
import { useState, useEffect } from "react";
function UsageDashboard() {
const { getUsageReport } = useMantle();
const [report, setReport] = useState(null);
useEffect(() => {
const fetchReport = async () => {
const result = await getUsageReport({
usageId: "usage_metric_api_calls",
period: "current_billing_period", // or "last_30_days", "last_7_days"
});
if (!("error" in result)) {
setReport(result.report);
}
};
fetchReport();
}, []);
if (!report) return
Loading usage data...
;
return (
API Usage This Period
Total Calls: {report.totalUsage}
Limit: {report.limit}
Remaining: {report.remaining}
);
}
```
--------------------------------
### Send Usage Event
Source: https://context7.com/hey-mantle/react/llms.txt
Sends a usage event to Mantle for metered billing or analytics tracking. Events can include custom properties for detailed usage reporting.
```APIDOC
## POST /api/usage/events
### Description
Sends a usage event to Mantle for metered billing or analytics tracking. Events can include custom properties for detailed usage reporting.
### Method
POST
### Endpoint
/api/usage/events
### Parameters
#### Request Body
- **eventName** (string) - Required - The name of the event.
- **properties** (object) - Optional - Custom properties for the event.
### Request Example
```json
{
"eventName": "page_view",
"properties": {
"path": "/home",
"referrer": ""
}
}
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the event was recorded successfully.
#### Response Example
```json
{
"success": true
}
```
```
--------------------------------
### Cancel Customer Subscription
Source: https://context7.com/hey-mantle/react/llms.txt
Use `cancelSubscription` to end a customer's current subscription. It accepts an optional `cancelReason` and returns the updated subscription object. Call `refetch` to refresh customer data after cancellation.
```tsx
import { useMantle } from "@heymantle/react";
function CancelSubscriptionButton() {
const { subscription, cancelSubscription, refetch } = useMantle();
const handleCancel = async () => {
if (!confirm("Are you sure you want to cancel your subscription?")) {
return;
}
const result = await cancelSubscription({
cancelReason: "No longer needed",
});
if ("error" in result) {
alert(`Failed to cancel: ${result.error}`);
return;
}
console.log("Subscription cancelled:", result.status);
await refetch(); // Refresh customer data
};
if (!subscription) return null;
return (
);
}
```
--------------------------------
### Evaluate and Sort Features
Source: https://context7.com/hey-mantle/react/llms.txt
Use `featureEnabled` to check if a feature is active and `featureSort` to sort features with enabled ones appearing first. Both functions require the feature object to have 'enabled' and 'value' properties.
```tsx
import { featureEnabled, featureSort } from "@heymantle/react";
function FeatureList({ features }) {
// Sort features: enabled first, then alphabetically
const sortedFeatures = [...features].sort(featureSort);
return (
);
}
// featureEnabled returns true if:
// - Boolean feature with value === true
// - Limit feature with value !== 0 (0 means disabled, -1 means unlimited)
```
--------------------------------
### Send Usage Event for Metered Billing
Source: https://context7.com/hey-mantle/react/llms.txt
The `sendUsageEvent` hook is for tracking customer usage for metered billing or analytics. Events can include custom properties. Use `useEffect` to track events like page views automatically.
```tsx
import { useMantle } from "@heymantle/react";
import { useEffect } from "react";
function UsageTracker() {
const { sendUsageEvent } = useMantle();
// Track page views
useEffect(() => {
sendUsageEvent({
eventName: "page_view",
properties: {
path: window.location.pathname,
referrer: document.referrer,
},
});
}, [window.location.pathname]);
// Track feature usage
const handleFeatureUse = async (featureName: string, quantity: number) => {
const result = await sendUsageEvent({
eventName: featureName,
properties: {
quantity,
timestamp: new Date().toISOString(),
},
});
if (result.success) {
console.log("Usage event recorded successfully");
}
};
return (
);
}
```
--------------------------------
### Cancel Subscription
Source: https://context7.com/hey-mantle/react/llms.txt
Cancels the current subscription with an optional cancellation reason. Returns the updated subscription object.
```APIDOC
## DELETE /api/subscriptions/current
### Description
Cancels the current subscription with an optional cancellation reason. Returns the updated subscription object.
### Method
DELETE
### Endpoint
/api/subscriptions/current
### Parameters
#### Request Body
- **cancelReason** (string) - Optional - The reason for cancellation.
### Request Example
```json
{
"cancelReason": "No longer needed"
}
```
### Response
#### Success Response (200)
- **status** (string) - The status of the subscription after cancellation.
#### Response Example
```json
{
"status": "canceled"
}
```
```
--------------------------------
### Check Feature Enabled Status with useMantle
Source: https://context7.com/hey-mantle/react/llms.txt
Use `isFeatureEnabled` to check if a feature is active for the customer. Supports boolean features and limit-based features by providing the current count.
```tsx
import { useMantle } from "@heymantle/react";
function FeatureGatedContent() {
const { isFeatureEnabled, limitForFeature, customer } = useMantle();
// Check boolean feature
const hasAdvancedAnalytics = isFeatureEnabled({
featureKey: "advanced_analytics",
});
// Check limit-based feature with current usage
const currentProductCount = customer?.usage?.products || 0;
const canAddMoreProducts = isFeatureEnabled({
featureKey: "max_products",
count: currentProductCount,
});
// Get the actual limit value
const productLimit = limitForFeature({ featureKey: "max_products" });
// Returns -1 if unlimited, or the numeric limit
return (
);
}
```
--------------------------------
### isFeatureEnabled
Source: https://context7.com/hey-mantle/react/llms.txt
Checks if a specific feature is enabled for the current customer. This function supports both boolean features and limit-based features by checking against usage counts.
```APIDOC
## isFeatureEnabled
### Description
Checks if a specific feature is enabled for the current customer based on their subscription plan. Supports both boolean features and limit-based features with usage counts.
### Method
`useMantle` hook
### Parameters
#### Function Parameters
- **featureKey** (string) - Required - The unique key identifying the feature.
- **count** (number) - Optional - The current usage count for limit-based features. If provided, checks if the current count is within the feature's limit.
### Returns
- **boolean**: `true` if the feature is enabled or the limit is not reached, `false` otherwise.
### Example Usage
```tsx
import { useMantle } from "@heymantle/react";
function FeatureGatedContent() {
const { isFeatureEnabled, limitForFeature, customer } = useMantle();
// Check boolean feature
const hasAdvancedAnalytics = isFeatureEnabled({
featureKey: "advanced_analytics",
});
// Check limit-based feature with current usage
const currentProductCount = customer?.usage?.products || 0;
const canAddMoreProducts = isFeatureEnabled({
featureKey: "max_products",
count: currentProductCount,
});
// Get the actual limit value
const productLimit = limitForFeature({ featureKey: "max_products" });
// Returns -1 if unlimited, or the numeric limit
return (
);
}
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.