Recipe
- Web
- Android
- iOS
- React Native
checkout.addEventListener('primer:state-change', (event) => {
const { isProcessing } = event.detail;
if (isProcessing) {
document.getElementById('loading-overlay').style.display = 'block';
} else {
document.getElementById('loading-overlay').style.display = 'none';
}
});
Loading during initialization
val checkout = rememberPrimerCheckoutController(clientToken)
val state by checkout.state.collectAsStateWithLifecycle()
when (state) {
is PrimerCheckoutState.Loading -> {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center,
) {
CircularProgressIndicator()
}
}
is PrimerCheckoutState.Ready -> {
PrimerCheckoutSheet(checkout = checkout)
}
}
Loading during form submission
val cardFormController = rememberCardFormController(checkout)
val formState by cardFormController.state.collectAsStateWithLifecycle()
Button(
onClick = { cardFormController.submit() },
enabled = formState.isFormValid && !formState.isLoading,
modifier = Modifier.fillMaxWidth(),
) {
if (formState.isLoading) {
CircularProgressIndicator(
modifier = Modifier.size(20.dp),
color = Color.White,
strokeWidth = 2.dp,
)
} else {
Text("Pay")
}
}
Loading during initialization
PrimerCheckout renders Primer’s managed loading screen while it initializes. For a custom inline layout, observe the PrimerCheckoutSession’s phase and show your own loading UI until it becomes .ready:@StateObject private var session: PrimerCheckoutSession
var body: some View {
ScrollView {
if session.phase == .initializing {
VStack(spacing: 16) {
ProgressView()
.scaleEffect(1.5)
Text("Loading payment methods...")
.font(.subheadline)
.foregroundColor(.secondary)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
PrimerCardForm()
}
}
.primerCheckoutSession(session) { state in
handle(state)
}
}
Loading during form submission
Drive the submit button from thePrimerCardFormSession injected into the slot, using state.isLoading and state.isValid:PrimerCardForm(submitButton: { session in
Button(action: { session.submit() }) {
if session.state.isLoading {
ProgressView()
.tint(.white)
} else {
Text("Pay")
}
}
.frame(maxWidth: .infinity, minHeight: 48)
.buttonStyle(.borderedProminent)
.disabled(!session.state.isValid || session.state.isLoading)
})
Loading during initialization
PrimerCheckoutSheet shows its own loading screen while it starts. For a custom layout, read isReady and error from usePrimerCheckout() and show your own loading UI until isReady is true:import { useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, Text, View } from 'react-native';
import {
PrimerCardFormProvider,
PrimerCheckoutProvider,
usePrimerCheckout,
} from '@primer-io/react-native';
import { CardPayment } from './CardPayment';
export function CheckoutScreen({ fetchClientToken }: { fetchClientToken: () => Promise<string> }) {
const [clientToken, setClientToken] = useState<string | null>(null);
const startCheckout = useCallback(async () => {
setClientToken(null);
setClientToken(await fetchClientToken());
}, [fetchClientToken]);
useEffect(() => {
void startCheckout();
}, [startCheckout]);
if (clientToken === null) return <ActivityIndicator />;
return (
<PrimerCheckoutProvider clientToken={clientToken}>
<CheckoutContent onTryAgain={startCheckout} />
</PrimerCheckoutProvider>
);
}
function CheckoutContent({ onTryAgain }: { onTryAgain: () => void }) {
const { isReady, error } = usePrimerCheckout();
if (error) {
return <Text>Checkout is not available right now.</Text>;
}
if (!isReady) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', gap: 16 }}>
<ActivityIndicator size="large" />
<Text>Loading payment methods...</Text>
</View>
);
}
return (
<PrimerCardFormProvider>
<CardPayment onTryAgain={onTryAgain} />
</PrimerCardFormProvider>
);
}
CardPayment is the component from the next sample, in CardPayment.tsx. After a failed payment, its “Try again” button calls startCheckout, which starts a new checkout with a new client token.Loading during form submission
Keep your own flag for the payment in progress. Set it when the shopper taps Pay and clear it only if the payment fails:import { useEffect, useState } from 'react';
import { ActivityIndicator, Button, Pressable, Text, View } from 'react-native';
import {
PrimerCardForm,
usePrimerCardForm,
usePrimerCheckout,
usePrimerPaymentMethod,
} from '@primer-io/react-native';
export function CardPayment({ onTryAgain }: { onTryAgain: () => void }) {
const { paymentOutcome } = usePrimerCheckout();
const card = usePrimerPaymentMethod('PAYMENT_CARD');
const cardForm = usePrimerCardForm();
const startCard = card.kind === 'card' && card.isAvailable ? card.start : undefined;
const [isPaying, setIsPaying] = useState(false);
useEffect(() => {
startCard?.();
}, [startCard]);
useEffect(() => {
if (paymentOutcome?.status === 'error') setIsPaying(false);
}, [paymentOutcome]);
const canPay = cardForm.isValid && !isPaying;
if (paymentOutcome?.status === 'success') return <Text>Payment complete.</Text>;
if (paymentOutcome?.status === 'error') {
return (
<View style={{ gap: 16, padding: 16 }}>
<Text>The payment didn't go through. Try again or use another card.</Text>
<Button title="Try again" onPress={onTryAgain} />
</View>
);
}
return (
<View style={{ gap: 16, padding: 16 }}>
<PrimerCardForm editable={!isPaying} />
<Pressable
disabled={!canPay}
onPress={() => {
setIsPaying(true);
void cardForm.submit();
}}
style={{
alignItems: 'center',
justifyContent: 'center',
minHeight: 48,
borderRadius: 8,
backgroundColor: '#1a73e8',
opacity: canPay || isPaying ? 1 : 0.5,
}}
>
{isPaying ? (
<ActivityIndicator color="#ffffff" />
) : (
<Text style={{ color: '#ffffff' }}>Pay</Text>
)}
</Pressable>
</View>
);
}
How it works
- Web
- Android
- iOS
- React Native
- Listen for the
primer:state-changeevent - Check the
isProcessingproperty from the event detail - Show your loading UI when
isProcessingistrue - Hide it when
isProcessingisfalse
The SDK provides two loading states:
| State Source | Property | When It’s True |
|---|---|---|
PrimerCheckoutController.state | PrimerCheckoutState.Loading | SDK initializing, fetching configuration |
PrimerCardFormController.state | isLoading | Payment is being processed after submit |
The SDK provides two loading states:
| State Source | Property | When It’s Active |
|---|---|---|
PrimerCheckoutSession | phase == .initializing | SDK initializing, fetching configuration |
PrimerCardFormSession.state | isLoading | From submit until the payment result, including while onBeforePaymentCreate waits for your decision |
Read these loading states:
| State Source | Property | When It’s Active |
|---|---|---|
usePrimerCheckout() | isReady === false | SDK initializing, loading the payment methods. If the start fails, error is set instead |
| Your own state | isPaying | From the Pay tap until usePrimerCheckout().paymentOutcome reports a failure |
usePrimerPaymentMethod(type) | isLoading | Native UI, bank selection and Klarna payment methods only, while the method loads or its payment runs |
Variations
Custom loading screen
- Web
- Android
- iOS
- React Native
const overlay = document.getElementById('loading-overlay');
checkout.addEventListener('primer:state-change', (event) => {
overlay.classList.toggle('visible', event.detail.isProcessing);
});
.loading-overlay {
opacity: 0;
visibility: hidden;
transition: opacity 0.2s, visibility 0.2s;
}
.loading-overlay.visible {
opacity: 1;
visibility: visible;
}
Override the
loading slot in PrimerCheckoutSheet to replace the default loading screen:PrimerCheckoutSheet(
checkout = checkout,
loading = {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(48.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
CircularProgressIndicator(
color = MaterialTheme.colorScheme.primary,
)
Spacer(Modifier.height(16.dp))
Text(
text = "Preparing your checkout...",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
},
onDismiss = { },
)
The managed
PrimerCheckout renders its own loading screen. To show a branded loading view, compose your UI inline with a PrimerCheckoutSession and render your view while phase is .initializing:@StateObject private var session: PrimerCheckoutSession
var body: some View {
ScrollView {
if session.phase == .initializing {
VStack(spacing: 16) {
ProgressView()
.controlSize(.large)
.tint(.accentColor)
Text("Preparing your checkout...")
.font(.body)
.foregroundColor(.secondary)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(.ultraThinMaterial)
} else {
PrimerCardForm()
}
}
.primerCheckoutSession(session) { state in
handle(state)
}
}
PrimerCheckoutSheet renders its own loading screen. To show a branded loading view, build your layout inline and render your view while isReady is false. PrimerLoadingScreen is the SDK’s loading screen, and it takes your own title, subtitle and icon:import { ActivityIndicator, Text, View } from 'react-native';
import {
PrimerCardFormProvider,
PrimerLoadingScreen,
usePrimerCheckout,
} from '@primer-io/react-native';
import { CardPayment } from './CardPayment';
function CheckoutContent({ onTryAgain }: { onTryAgain: () => void }) {
const { isReady, error } = usePrimerCheckout();
if (error) {
return <Text>Checkout is not available right now.</Text>;
}
if (!isReady) {
return (
<View style={{ flex: 1, justifyContent: 'center' }}>
<PrimerLoadingScreen
title="Preparing your checkout..."
subtitle="This only takes a moment."
icon={<ActivityIndicator size="large" color="#6c5ce7" />}
/>
</View>
);
}
return (
<PrimerCardFormProvider>
<CardPayment onTryAgain={onTryAgain} />
</PrimerCardFormProvider>
);
}
CardPayment is the component from the recipe above. Render this CheckoutContent in place of the recipe’s, inside its CheckoutScreen.Inline loading overlay
- Web
- Android
- iOS
- React Native
checkout.addEventListener('primer:state-change', (event) => {
const { isProcessing } = event.detail;
// Disable all inputs on the page during processing
document.querySelectorAll('input, button, select').forEach((el) => {
el.disabled = isProcessing;
});
});
For inline integrations, you manage the loading UI yourself. This example shows a semi-transparent overlay during form submission:
@Composable
fun InlineCheckoutWithLoading(clientToken: String) {
val checkout = rememberPrimerCheckoutController(clientToken)
val state by checkout.state.collectAsStateWithLifecycle()
LaunchedEffect(state) {
when (state) {
is PrimerCheckoutState.Success -> { }
is PrimerCheckoutState.Failure -> { }
else -> Unit
}
}
when (state) {
is PrimerCheckoutState.Loading -> {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center,
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
CircularProgressIndicator()
Spacer(Modifier.height(12.dp))
Text("Loading payment methods...")
}
}
}
is PrimerCheckoutState.Ready -> {
PrimerCheckoutHost(
checkout = checkout,
) {
val cardFormController = rememberCardFormController(checkout)
val formState by cardFormController.state.collectAsStateWithLifecycle()
Box {
Column(Modifier.padding(16.dp)) {
PrimerCardForm(
controller = cardFormController,
submitButton = {
Button(
onClick = { cardFormController.submit() },
enabled = formState.isFormValid && !formState.isLoading,
modifier = Modifier.fillMaxWidth(),
) {
if (formState.isLoading) {
CircularProgressIndicator(
modifier = Modifier.size(20.dp),
color = Color.White,
strokeWidth = 2.dp,
)
} else {
Text("Pay")
}
}
},
)
}
if (formState.isLoading) {
Box(
modifier = Modifier
.matchParentSize()
.background(Color.Black.copy(alpha = 0.3f)),
contentAlignment = Alignment.Center,
) {
Card(
modifier = Modifier.padding(32.dp),
) {
Column(
modifier = Modifier.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
CircularProgressIndicator()
Spacer(Modifier.height(12.dp))
Text("Processing payment...")
}
}
}
}
}
}
}
}
}
For inline integrations, once the payment starts, the SDK shows its own processing screen in a sheet above your layout. The sheet then shows the success or error screen. To hide the success and error screens, pass
PrimerSettings(uiOptions: PrimerUIOptions(isSuccessScreenEnabled: false, isErrorScreenEnabled: false)) as the settings of PrimerCheckoutSession. The processing screen always shows while a payment runs. The shopper cannot swipe that sheet away while the payment processes.isLoading on the PrimerCardFormSession turns true as soon as the shopper submits. It stays true while onBeforePaymentCreate waits for your decision. Use it to dim the form, disable your controls, or show a loading card until the SDK sheet appears, as this example does:struct InlineCheckoutWithLoading: View {
@StateObject private var session: PrimerCheckoutSession
init(clientToken: String) {
_session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken))
}
var body: some View {
ScrollView {
PrimerCardForm(
cardDetails: { session in
VStack(spacing: 16) {
CardFormDefaults.cardNumber(session)
HStack(spacing: 12) {
CardFormDefaults.expiryDate(session)
CardFormDefaults.cvv(session)
}
}
},
submitButton: { session in
SubmitWithOverlay(session: session)
}
)
.padding()
}
.primerCheckoutSession(session) { state in
// Handle the terminal PrimerCheckoutState.
}
}
}
struct SubmitWithOverlay: View {
@ObservedObject var session: PrimerCardFormSession
var body: some View {
ZStack {
Button(action: { session.submit() }) {
Text("Pay")
.frame(maxWidth: .infinity, minHeight: 48)
}
.buttonStyle(.borderedProminent)
.disabled(!session.state.isValid || session.state.isLoading)
if session.state.isLoading {
Color.black.opacity(0.3)
.ignoresSafeArea()
VStack(spacing: 12) {
ProgressView()
Text("Processing payment...")
.font(.subheadline)
}
.padding(24)
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12))
}
}
}
}
PrimerCheckoutSheet shows a processing screen while a payment runs, then a success or error screen. To skip the result screens, set isSuccessScreenEnabled or isErrorScreenEnabled to false in settings.uiOptions. See Result screens.In a custom layout, you show the processing state yourself. Set your own flag when the shopper taps Pay, and clear it only if the payment fails. Use it to lock the fields with editable, disable your controls, and show an overlay, as this example does:import { useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, Button, StyleSheet, Text, View } from 'react-native';
import {
PrimerCardForm,
PrimerCardFormProvider,
PrimerCheckoutProvider,
usePrimerCardForm,
usePrimerCheckout,
usePrimerPaymentMethod,
} from '@primer-io/react-native';
export function InlineCheckoutWithLoading({ fetchClientToken }: { fetchClientToken: () => Promise<string> }) {
const [clientToken, setClientToken] = useState<string | null>(null);
const startCheckout = useCallback(async () => {
setClientToken(null);
setClientToken(await fetchClientToken());
}, [fetchClientToken]);
useEffect(() => {
void startCheckout();
}, [startCheckout]);
if (clientToken === null) return <ActivityIndicator />;
return (
<PrimerCheckoutProvider clientToken={clientToken}>
<PrimerCardFormProvider>
<CardFormWithOverlay onTryAgain={startCheckout} />
</PrimerCardFormProvider>
</PrimerCheckoutProvider>
);
}
function CardFormWithOverlay({ onTryAgain }: { onTryAgain: () => void }) {
const { isReady, paymentOutcome } = usePrimerCheckout();
const card = usePrimerPaymentMethod('PAYMENT_CARD');
const cardForm = usePrimerCardForm();
const startCard = card.kind === 'card' && card.isAvailable ? card.start : undefined;
const [isPaying, setIsPaying] = useState(false);
useEffect(() => {
startCard?.();
}, [startCard]);
useEffect(() => {
if (paymentOutcome?.status === 'error') setIsPaying(false);
}, [paymentOutcome]);
if (!isReady) {
return (
<View style={styles.centered}>
<ActivityIndicator size="large" />
<Text>Loading payment methods...</Text>
</View>
);
}
if (paymentOutcome?.status === 'success') return <Text>Payment complete.</Text>;
if (paymentOutcome?.status === 'error') {
return (
<View style={styles.container}>
<Text>The payment didn't go through. Try again or use another card.</Text>
<Button title="Try again" onPress={onTryAgain} />
</View>
);
}
return (
<View style={styles.container}>
<PrimerCardForm editable={!isPaying} />
<Button
title="Pay"
disabled={!cardForm.isValid || isPaying}
onPress={() => {
setIsPaying(true);
void cardForm.submit();
}}
/>
{isPaying && (
<View style={styles.overlay}>
<View style={styles.overlayCard}>
<ActivityIndicator size="large" />
<Text>Processing payment...</Text>
</View>
</View>
)}
</View>
);
}
const styles = StyleSheet.create({
centered: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 12 },
container: { gap: 16, padding: 16 },
overlay: {
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'rgba(0, 0, 0, 0.3)',
},
overlayCard: {
alignItems: 'center',
gap: 12,
padding: 24,
borderRadius: 12,
backgroundColor: '#ffffff',
},
});
Show processing message
- Web
- Android
- iOS
- React Native
checkout.addEventListener('primer:state-change', (event) => {
const statusEl = document.getElementById('status-message');
if (event.detail.isProcessing) {
statusEl.textContent = 'Processing your payment...';
statusEl.className = 'status processing';
} else if (event.detail.isSuccessful) {
statusEl.textContent = 'Payment successful!';
statusEl.className = 'status success';
} else {
statusEl.textContent = '';
statusEl.className = 'status';
}
});
val checkout = rememberPrimerCheckoutController(clientToken)
val state by checkout.state.collectAsStateWithLifecycle()
val cardFormController = rememberCardFormController(checkout)
val formState by cardFormController.state.collectAsStateWithLifecycle()
when {
state is PrimerCheckoutState.Loading -> Text("Loading payment methods...")
formState.isLoading -> Text("Processing payment...")
}
Observe the session
phase and the card form session’s state.isLoading to drive a status message. Observe the PrimerCardFormSession in its own view, because PrimerCheckoutSession does not publish card form changes:struct StatusMessage: View {
@ObservedObject var session: PrimerCheckoutSession
var body: some View {
if session.phase == .initializing {
Text("Loading payment methods...")
} else if let cardForm = session.cardForm {
CardFormStatus(cardForm: cardForm)
}
}
}
struct CardFormStatus: View {
@ObservedObject var cardForm: PrimerCardFormSession
var body: some View {
if cardForm.state.isLoading {
Text("Processing payment...")
}
}
}
Derive the message from
isReady and the isPaying flag of your Pay button. Render StatusMessage where it is mounted while the checkout loads, and pass it the flag: <StatusMessage isPaying={isPaying} />. Inside CardPayment from the recipe above, only “Processing payment…” shows, because CardPayment renders once the checkout is ready.import { Text } from 'react-native';
import { usePrimerCheckout } from '@primer-io/react-native';
function StatusMessage({ isPaying }: { isPaying: boolean }) {
const { isReady } = usePrimerCheckout();
if (!isReady) {
return <Text>Loading payment methods...</Text>;
}
if (isPaying) {
return <Text>Processing payment...</Text>;
}
return null;
}
See also
Disable external buttons
Prevent double submission during payment processing
Events guide
Handle payment lifecycle events