Skip to main content

Imperative Ref

AccruPay forwards a ref that exposes submitPayment() imperatively. Use this when you need to trigger submission from outside the AccruPay component tree, or programmatically from code that cannot call useAccruPay.

tip

For most checkout forms, useAccruPay + SubmitButton is the simpler approach. Use the imperative ref only when you need external control over submission.

AccruPayRef type

type AccruPayRef = {
submitPayment: (params?: AccruPayTransactionSubmitParams) => Promise<any>;
};

This is the same submitPayment exposed by useAccruPay — identical behavior, identical error handling.

Usage

import { useRef } from 'react';
import {
AccruPay,
CardholderName,
CardNumber,
CardExpiry,
CardCVC,
} from '@accrupay/react';
import type { AccruPayRef } from '@accrupay/react';

export function Checkout({ sessionId }: { sessionId: string }) {
const payRef = useRef<AccruPayRef>(null);

async function handleExternalSubmit() {
if (!payRef.current) return;
try {
const result = await payRef.current.submitPayment();
console.log('Payment succeeded', result);
} catch (err) {
console.error('Payment failed', err);
}
}

return (
<div>
<AccruPay
ref={payRef}
merchantPublicId={process.env.NEXT_PUBLIC_ACCRUPAY_MERCHANT_ID!}
transactionSessionId={sessionId}
>
<CardholderName placeholder="Name on card" />
<CardNumber />
<CardExpiry />
<CardCVC />
</AccruPay>

{/* Button lives outside the AccruPay tree */}
<button onClick={handleExternalSubmit}>
Pay now
</button>
</div>
);
}

Passing billing data

The ref's submitPayment accepts the same optional params as the hook version:

await payRef.current.submitPayment({
billing: {
firstName: 'Jane',
lastName: 'Smith',
email: 'jane@example.com',
country: 'US',
},
});

Error handling

submitPayment() throws on failure — wrap every call in try/catch. The thrown value is an Error with the provider's message.

If you also render useAccruPay inside the tree, the error field will be updated automatically after a failed submission, regardless of whether you called submitPayment via the ref or the hook.

When to use the ref

ScenarioRecommendation
Pay button inside the <AccruPay> treeSubmitButton or useAccruPay
Pay button outside the <AccruPay> treeImperative ref
Multi-step form where submission is in a parent componentImperative ref
Programmatic submission (e.g. after async validation)Either — ref if outside the tree, hook if inside