Skip to main content

useEasy Hook

The useEasy hook is the primary way to access Easy SDK functionality in your React Native components. It provides methods for customer management, payment processing, product management, and more.

Basic Usage

import { useEasy } from "@easylabs/react-native";

function MyComponent() {
const { checkout, createCustomer, createTransfer } = useEasy();

// Use the methods
}
Requirements

The useEasy hook must be used within a component that is wrapped by EasyProvider.

Available Methods

The hook returns an object with all Easy SDK methods. For detailed documentation of each method, see the API Reference sections.

Customer Management

const {
createCustomer,
updateCustomer,
getCustomer,
getCustomers,
getCustomerPaymentInstruments,
getCustomerOrders,
} = useEasy();
  • createCustomer - Create a new customer
  • updateCustomer - Update customer information
  • getCustomer - Retrieve a customer by ID
  • getCustomers - List all customers
  • getCustomerPaymentInstruments - Get customer's payment methods
  • getCustomerOrders - Get customer's order history

Payment Processing

const {
checkout,
createPaymentInstrument,
updatePaymentInstrument,
tokenizePaymentInstrument,
} = useEasy();
  • checkout - Process a complete checkout (recommended)
  • createPaymentInstrument - Create a payment method
  • updatePaymentInstrument - Update payment method details
  • tokenizePaymentInstrument - Tokenize payment data

Transfers

const { createTransfer, getTransfer, getTransfers, updateTransferTags } =
useEasy();
  • createTransfer - Create a new payment transfer
  • getTransfer - Get transfer details
  • getTransfers - List all transfers
  • updateTransferTags - Update transfer metadata

Products & Pricing

const {
getProducts,
getProduct,
createProduct,
updateProduct,
archiveProduct,
getProductPrices,
createProductPrice,
updateProductPrice,
} = useEasy();
  • getProducts - List all products
  • getProduct - Get product details
  • createProduct - Create a new product
  • updateProduct - Update product information
  • archiveProduct - Archive a product
  • getProductPrices - List prices for products
  • createProductPrice - Create a new price
  • updateProductPrice - Update price details

Subscriptions

const {
getSubscription,
getSubscriptions,
getCustomerSubscriptions,
createSubscription,
cancelSubscription,
createSubscriptionPlan,
getSubscriptionPlans,
updateSubscriptionPlan,
} = useEasy();
  • getSubscription - Get subscription details
  • getSubscriptions - List all subscriptions
  • getCustomerSubscriptions - Get customer's subscriptions
  • createSubscription - Create a new subscription
  • cancelSubscription - Cancel a subscription
  • createSubscriptionPlan - Create a subscription plan
  • getSubscriptionPlans - List subscription plans
  • updateSubscriptionPlan - Update plan details

Example Usage

Create a Customer

import { useEasy } from "@easylabs/react-native";
import { Button, Alert } from "react-native";

function CreateCustomerButton() {
const { createCustomer } = useEasy();

const handlePress = async () => {
try {
const result = await createCustomer({
first_name: "Jane",
last_name: "Smith",
email: "[email protected]",
phone: "+1234567890",
});

Alert.alert("Success", `Customer created: ${result.data.id}`);
} catch (error) {
Alert.alert("Error", error.message);
}
};

return <Button title="Create Customer" onPress={handlePress} />;
}

Process a Payment

import { useEasy, CardNumberElement } from "@easylabs/react-native";
import { useRef, useState } from "react";
import { View, Button, Alert } from "react-native";

function PaymentScreen() {
const { checkout } = useEasy();
const cardNumberRef = useRef(null);
const expiryRef = useRef(null);
const cvcRef = useRef(null);
const [loading, setLoading] = useState(false);

const handlePayment = async () => {
setLoading(true);

try {
const result = await checkout({
customer_creation: true,
customer_details: {
first_name: "John",
last_name: "Doe",
email: "[email protected]",
},
source: {
type: "PAYMENT_CARD",
cardNumberElement: cardNumberRef,
cardExpirationDateElement: expiryRef,
cardVerificationCodeElement: cvcRef,
name: "Primary Card",
},
line_items: [{ price_id: "price_123", quantity: 1 }],
});

Alert.alert("Success", "Payment processed!");
} catch (error) {
Alert.alert("Error", error.message);
} finally {
setLoading(false);
}
};

return (
<View>
{/* Card input elements */}
<Button
title={loading ? "Processing..." : "Pay Now"}
onPress={handlePayment}
disabled={loading}
/>
</View>
);
}

List Products

import { useEasy } from "@easylabs/react-native";
import { useEffect, useState } from "react";
import { FlatList, Text, View } from "react-native";

function ProductList() {
const { getProducts } = useEasy();
const [products, setProducts] = useState([]);

useEffect(() => {
loadProducts();
}, []);

const loadProducts = async () => {
try {
const result = await getProducts({ limit: 20 });
setProducts(result.data);
} catch (error) {
console.error("Failed to load products:", error);
}
};

return (
<FlatList
data={products}
keyExtractor={(item) => item.id}
renderItem={({ item }) => (
<View>
<Text>{item.name}</Text>
<Text>{item.description}</Text>
</View>
)}
/>
);
}

Error Handling

All methods return promises and can throw errors. Always wrap calls in try-catch blocks:

const { createCustomer } = useEasy();

try {
const result = await createCustomer({...});
// Handle success
} catch (error) {
// Handle error
console.error(error.message);
}

Common error scenarios:

  • Invalid API key
  • Missing required fields
  • Network errors
  • Payment processing failures

TypeScript Support

All methods are fully typed when using TypeScript:

import { useEasy } from "@easylabs/react-native";
import type { CreateCustomer, CustomerData } from "@easylabs/react-native";

function MyComponent() {
const { createCustomer } = useEasy();

// TypeScript enforces correct types
const customer: CreateCustomer = {
first_name: "John",
last_name: "Doe",
email: "[email protected]",
};

// Return type is inferred
const result = await createCustomer(customer); // Promise<ApiResponse<CustomerData>>
}

Best Practices

1. Destructure Only What You Need

// ✅ Good
const { checkout, createCustomer } = useEasy();

// ❌ Avoid
const easy = useEasy();

2. Use Loading States

const [loading, setLoading] = useState(false);

const handleAction = async () => {
setLoading(true);
try {
await someMethod();
} finally {
setLoading(false);
}
};

3. Handle Errors Gracefully

import { Alert } from "react-native";

try {
await checkout({...});
Alert.alert("Success", "Payment processed!");
} catch (error) {
Alert.alert("Error", "Payment failed. Please try again.");
}

4. Memoize Callbacks

import { useCallback } from "react";

const { createCustomer } = useEasy();

const handleCreateCustomer = useCallback(
async (data) => {
await createCustomer(data);
},
[createCustomer],
);

Next Steps