> ## Documentation Index
> Fetch the complete documentation index at: https://primer.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Pre-fill cardholder name

> Automatically fill in the cardholder name from user profile data.

Pre-populate the cardholder name field with data from your user's profile to reduce friction at checkout.

## Recipe

> [tab] Web
>
> ```javascript theme={"dark"}
> checkout.addEventListener('primer:ready', (event) => {
>   const primer = event.detail;
>
>   const user = getAuthenticatedUser();
>   if (user?.fullName) {
>     primer.setCardholderName(user.fullName);
>   }
> });
> ```

> [tab] Android
>
> ```kotlin theme={"dark"}
> val checkout = rememberPrimerCheckoutController(clientToken)
> val cardFormController = rememberCardFormController(checkout)
>
> LaunchedEffect(cardFormController) {
>     cardFormController.updateCardholderName(userProfile.fullName)
> }
> ```

> [tab] iOS
>
> ```swift theme={"dark"}
> @StateObject private var session: PrimerCheckoutSession
>
> init(clientToken: String) {
>   _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken))
> }
>
> var body: some View {
>   ScrollView {
>     PrimerCardForm()
>   }
>   .primerCheckoutSession(session) { state in
>     // Handle .success and .dismissed. After .ready, a .failure ends one attempt and the customer can retry.
>   }
>   .onChange(of: session.phase) { phase in
>     guard phase == .ready, let cardForm = session.cardForm else { return }
>
>     // The client session already carries the customer you attached on your backend.
>     let customer = session.clientSession?.customer
>     let name = [customer?.firstName, customer?.lastName]
>       .compactMap { $0 }
>       .joined(separator: " ")
>
>     if !name.isEmpty {
>       cardForm.updateCardholderName(name)
>     }
>   }
> }
> ```

> [tab] React Native
>
> Pre-fill the name in your card layout. Put the pre-fill hook in its own file, `usePrefillCardholderName.ts`, so the variations below can reuse it:
>
> ```tsx theme={"dark"}
> import { useEffect, useRef } from 'react';
> import { usePrimerCardForm } from '@primer-io/react-native';
>
> export function usePrefillCardholderName(name: string) {
>   const { requiredFields, isCardholderNameVisible, updateCardholderName } = usePrimerCardForm();
>   const prefilled = useRef(false);
>   const isCardFormActive = requiredFields.length > 0;
>
>   useEffect(() => {
>     if (prefilled.current || !isCardFormActive || !isCardholderNameVisible || !name) return;
>     prefilled.current = true;
>     updateCardholderName(name);
>   }, [isCardFormActive, isCardholderNameVisible, name, updateCardholderName]);
> }
> ```
>
> Then call it from your card layout:
>
> ```tsx theme={"dark"}
> import { useCallback, useEffect, useState } from 'react';
> import { ActivityIndicator, Button, Text, View } from 'react-native';
> import {
>   PrimerCardForm,
>   PrimerCardFormProvider,
>   PrimerCheckoutProvider,
>   usePrimerCardForm,
>   usePrimerCheckout,
>   usePrimerPaymentMethod,
> } from '@primer-io/react-native';
> import { usePrefillCardholderName } from './usePrefillCardholderName';
>
> export function PrefilledCardScreen({ 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>
>         <PrefilledCardForm onTryAgain={startCheckout} />
>       </PrimerCardFormProvider>
>     </PrimerCheckoutProvider>
>   );
> }
>
> function PrefilledCardForm({ onTryAgain }: { onTryAgain: () => void }) {
>   const { clientSession, 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 customer = clientSession?.customer;
>   usePrefillCardholderName([customer?.firstName, customer?.lastName].filter(Boolean).join(' '));
>
>   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} />
>       <Button
>         title="Pay"
>         disabled={!cardForm.isValid || isPaying}
>         onPress={() => {
>           setIsPaying(true);
>           void cardForm.submit();
>         }}
>       />
>     </View>
>   );
> }
> ```
>
> After a failed payment, "Try again" starts a new checkout with a new client token.

## How it works

> [tab] Web
>
> 1. Listen for the `primer:ready` event to access the Primer SDK instance
>
> 2. Retrieve the user's name from your authentication system or profile data
>
> 3. Call `primer.setCardholderName()` with the name value
>
> > [!NOTE]
> >
> > When using `setCardholderName()`, you don't need to include the `<primer-input-card-holder-name>` component in your form if you don't want users to edit the name.

> [tab] Android
>
> 1. Create a `PrimerCardFormController` using `rememberCardFormController()`
>
> 2. Call `updateCardholderName()` with the user's name inside a `LaunchedEffect`
>
> 3. The field will display the prefilled name and the user can edit it if needed
>
> > [!NOTE]
> >
> > `updateCardholderName()` sets the field value programmatically. The customer can still edit the prefilled name. The same approach works for other fields -- use `updateCardNumber()`, `updateExpiryDate()`, or `updateCvv()` as needed.

> [tab] iOS
>
> 1. Hold a `PrimerCheckoutSession` as a `@StateObject` and apply the `.primerCheckoutSession(_:theme:onCompletion:)` modifier
> 2. Once the session reaches `.ready`, read the customer from [`session.clientSession`](https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/primer-checkout-state#primerclientsession) -- these are the details you attached when you created the client session, so there is nothing to pass in from your own screen
> 3. The `cardForm` sub-session (a [`PrimerCardFormSession`](https://primer.io/docs/sdk/ios-checkout/v3.0.0-beta/api/card-form/card-form-session)) is available at the same point -- call `updateCardholderName()` on it
> 4. The field shows the name, the customer can still edit it, and the form counts the field as filled, so the submit button is not held back
>
> Every property on the client session is optional, so build the name defensively -- a session created
> without a customer leaves the field untouched rather than writing an empty string.
>
> > [!NOTE]
> >
> > The other setters on `PrimerCardFormSession` work the same way: `updateCardNumber()`,
> > `updateExpiryDate()`, `updateCvv()`, `updateFirstName()`, `updateLastName()`,
> > `updateAddressLine1()`, `updateAddressLine2()`, `updateCity()`, `updateState()`,
> > `updatePostalCode()` and `updateCountryCode()`. Each one changes what its
> > field shows and counts the field as filled. `updateCountryCode()` takes a country code such as `"GB"`. If the
> > SDK does not recognize the code, the country field stays as it was. A write that lands while the
> > customer is typing in a text field does not override their keystrokes.
> >
> > The values you read back are redacted: `cardForm.state` carries an empty card number until the
> > number is complete and valid, then a masked one, and never carries the CVV.

> [tab] React Native
>
> 1. Wrap your layout in `PrimerCheckoutProvider` and `PrimerCardFormProvider`, and call `start()` on [`usePrimerPaymentMethod('PAYMENT_CARD')`](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/payment-methods/use-primer-payment-method) to activate the card form
> 2. Read the customer from [`usePrimerCheckout().clientSession`](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/use-primer-checkout). These are the details you attached when you created the client session, so there is nothing to pass in from your own screen
> 3. Wait until the card form is active: [`usePrimerCardForm().requiredFields`](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/card-form/use-primer-card-form) stays empty until then. Then call `updateCardholderName()` once
> 4. The field shows the name and the customer can still edit it. The SDK sends the name with the other card fields to the native SDK, which validates them
>
> `clientSession` is `null` until the client session loads, and every customer field is optional, so build the name defensively. A session without a customer name leaves the field empty rather than writing an empty string. When the client session's `CARD_INFORMATION` checkout module turns off the cardholder name, `isCardholderNameVisible` is `false`, `PrimerCardForm` hides the field, and the recipe skips the pre-fill.
>
> > [!NOTE]
> >
> > `usePrimerCardForm()` has a setter for each card field: `updateCardNumber()`, `updateExpiryDate()`, `updateCVV()` and `updateCardholderName()`. Each one changes what its field shows.

## Variations

### Pre-fill from shipping address

> [tab] Web
>
> ```javascript theme={"dark"}
> checkout.addEventListener('primer:ready', (event) => {
>   const primer = event.detail;
>
>   // Get name from shipping form
>   const shippingName = document.getElementById('shipping-name').value;
>   if (shippingName) {
>     primer.setCardholderName(shippingName);
>   }
> });
> ```

> [tab] Android
>
> ```kotlin theme={"dark"}
> LaunchedEffect(cardFormController) {
>     cardFormController.updateCardholderName(shippingAddress.fullName)
> }
> ```

> [tab] iOS
>
> ```swift theme={"dark"}
> .onChange(of: session.phase) { phase in
>   guard phase == .ready, let cardForm = session.cardForm else { return }
>
>   let shipping = session.clientSession?.customer?.shippingAddress
>   let name = [shipping?.firstName, shipping?.lastName]
>     .compactMap { $0 }
>     .joined(separator: " ")
>
>   if !name.isEmpty {
>     cardForm.updateCardholderName(name)
>   }
> }
> ```

> [tab] React Native
>
> Build the name from the shipping address instead, and pass it to `usePrefillCardholderName` from the recipe above:
>
> ```tsx theme={"dark"}
> const { clientSession } = usePrimerCheckout();
>
> const shipping = clientSession?.customer?.shippingAddress;
> usePrefillCardholderName([shipping?.firstName, shipping?.lastName].filter(Boolean).join(' '));
> ```

### Pre-fill with editable field

If you want to pre-fill but still allow editing, include the cardholder name input and set an initial value:

> [tab] Web
>
> ```javascript theme={"dark"}
> checkout.addEventListener('primer:ready', (event) => {
>   const primer = event.detail;
>   const user = getAuthenticatedUser();
>
>   if (user?.fullName) {
>     // Pre-fill the value
>     primer.setCardholderName(user.fullName);
>
>     // The <primer-input-card-holder-name> component will show this value
>     // and users can still edit it
>   }
> });
> ```

> [tab] Android
>
> ```kotlin theme={"dark"}
> val state by checkout.state.collectAsStateWithLifecycle()
>
> LaunchedEffect(state) {
>     when (state) {
>         is PrimerCheckoutState.Success -> { }
>         is PrimerCheckoutState.Failure -> { }
>         else -> Unit
>     }
> }
>
> PrimerCheckoutHost(
>     checkout = checkout,
> ) {
>     val cardFormController = rememberCardFormController(checkout)
>
>     LaunchedEffect(cardFormController) {
>         cardFormController.updateCardholderName(userProfile.fullName)
>     }
>
>     PrimerCardForm(
>         controller = cardFormController,
>         cardDetails = {
>             Column {
>                 CardFormDefaults.CardholderField(cardFormController)
>                 Spacer(Modifier.height(8.dp))
>                 CardFormDefaults.CardNumberField(cardFormController)
>                 Spacer(Modifier.height(8.dp))
>                 Row(Modifier.fillMaxWidth()) {
>                     CardFormDefaults.ExpiryField(
>                         cardFormController,
>                         Modifier.weight(1f),
>                     )
>                     Spacer(Modifier.width(8.dp))
>                     CardFormDefaults.CvvField(
>                         cardFormController,
>                         Modifier.weight(1f),
>                     )
>                 }
>             }
>         },
>     )
> }
> ```

> [tab] iOS
>
> The prefilled field is always editable. Recomposing the `cardDetails` slot is how you decide where
> the name sits -- here it leads the form, so the customer sees what was filled in for them first:
>
> ```swift theme={"dark"}
> struct PrefilledCardFormScreen: View {
>   @StateObject private var session: PrimerCheckoutSession
>
>   init(clientToken: String) {
>     _session = StateObject(wrappedValue: PrimerCheckoutSession(clientToken: clientToken))
>   }
>
>   var body: some View {
>     ScrollView {
>       PrimerCardForm(cardDetails: { formSession in
>         VStack(spacing: 16) {
>           CardFormDefaults.cardholderName(formSession)
>           CardFormDefaults.cardNumber(formSession)
>           HStack(spacing: 12) {
>             CardFormDefaults.expiryDate(formSession)
>             CardFormDefaults.cvv(formSession)
>           }
>           CardFormDefaults.cardNetwork(formSession)
>         }
>         .padding()
>       })
>     }
>     .primerCheckoutSession(session) { state in
>       // Handle .success and .dismissed. After .ready, a .failure ends one attempt and the customer can retry.
>     }
>     .onChange(of: session.phase) { phase in
>       guard phase == .ready, let cardForm = session.cardForm else { return }
>
>       let customer = session.clientSession?.customer
>       let name = [customer?.firstName, customer?.lastName]
>         .compactMap { $0 }
>         .joined(separator: " ")
>
>       if !name.isEmpty {
>         cardForm.updateCardholderName(name)
>       }
>     }
>   }
> }
> ```
>
> > [!NOTE]
> >
> > When you recompose the individual card fields, add `CardFormDefaults.cardNetwork(formSession)` so co-badged cards still get a network selector -- the built-in one is suppressed once you replace the default `cardDetails` section.

> [tab] React Native
>
> The pre-filled field is always editable. `PrimerCardForm` places the cardholder name last. To lead with the name, so the customer sees what was filled in for them first, compose the [card inputs](https://primer.io/docs/sdk/react-native-checkout/v3.0.0-beta/api/card-form/card-inputs.md) yourself. `usePrefillCardholderName` is the hook from the recipe above, in `usePrefillCardholderName.ts`:
>
> ```tsx theme={"dark"}
> import { useCallback, useEffect, useState } from 'react';
> import { ActivityIndicator, Button, Text, View } from 'react-native';
> import {
>   PrimerCardFormProvider,
>   PrimerCardholderNameInput,
>   PrimerCardNumberInput,
>   PrimerCheckoutProvider,
>   PrimerCVVInput,
>   PrimerExpiryDateInput,
>   usePrimerCardForm,
>   usePrimerCheckout,
>   usePrimerPaymentMethod,
> } from '@primer-io/react-native';
> import { usePrefillCardholderName } from './usePrefillCardholderName';
>
> export function PrefilledCardFormScreen({ 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>
>         <NameFirstCardForm onTryAgain={startCheckout} />
>       </PrimerCardFormProvider>
>     </PrimerCheckoutProvider>
>   );
> }
>
> function NameFirstCardForm({ onTryAgain }: { onTryAgain: () => void }) {
>   const { clientSession, 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 customer = clientSession?.customer;
>   usePrefillCardholderName([customer?.firstName, customer?.lastName].filter(Boolean).join(' '));
>
>   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: 12, padding: 16 }}>
>       {cardForm.isCardholderNameVisible && <PrimerCardholderNameInput editable={!isPaying} />}
>       <PrimerCardNumberInput editable={!isPaying} />
>       <View style={{ flexDirection: 'row', gap: 12 }}>
>         <PrimerExpiryDateInput editable={!isPaying} style={{ flex: 1 }} />
>         <PrimerCVVInput label={cardForm.descriptor.cvvLabel} editable={!isPaying} style={{ flex: 1 }} />
>       </View>
>       <Button
>         title="Pay"
>         disabled={!cardForm.isValid || isPaying}
>         onPress={() => {
>           setIsPaying(true);
>           void cardForm.submit();
>         }}
>       />
>     </View>
>   );
> }
> ```
>
> > [!NOTE]
> >
> > Render `PrimerCardholderNameInput` only when `isCardholderNameVisible` is `true`. `PrimerCardNumberInput` already contains the co-badged network selector, so don't add `PrimerCardNetworkSelector` next to it.

## See also

> [card] [Build a custom card form](https://primer.io/docs/checkout/primer-checkout/guides-and-recipes/build-custom-card-form.md)
>
> Step-by-step guide to building a fully custom card form

> [card] [SDK options](https://primer.io/docs/checkout/primer-checkout/configuration/sdk-options.md)
>
> All available SDK configuration options


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.