# Pre-filled Data

Canonical page: https://docs.ovok.com/native-sdk/guide/components/auth/register/examples/pre-filled-data

Learn how to handle registration with pre-existing data and partial user information.

## Basic Pre-filled Registration [#basic-pre-filled-registration]

Use default values to pre-populate form fields:

```tsx
import React from "react";
import { View, Text } from "react-native";
import { Register } from "@ovok/native";

export const PreFilledRegistration = () => {
  const existingUserData = {
    name: "John",
    surname: "Doe",
    email: "john.doe@example.com",
  };

  return (
    <Register>
      <Register.Header>
        <Register.Header.Title>
          Complete Your Registration
        </Register.Header.Title>
        <Register.Header.Description>
          Just add a password to finish setting up your account
        </Register.Header.Description>
      </Register.Header>

      <Register.EmailForm
        defaultValues={existingUserData}
        tenantCode="your-tenant-code"
        onSuccess={(response) =>
          console.log("Registration completed:", response)
        }
        onError={(error) => console.error("Registration failed:", error)}
      >
        {/* Only password fields will be shown since other fields are pre-filled */}
        <Register.EmailForm.Inputs />
        <Register.EmailForm.RegisterButton />
      </Register.EmailForm>
    </Register>
  );
};
```

## Social Login Flow [#social-login-flow]

Handle registration after social authentication:

```tsx
import React from "react";
import { Register } from "@ovok/native";

export const SocialRegistrationCompletion = () => {
  // Data received from social login (Google, Apple, etc.)
  const socialUserData = {
    name: "Jane",
    surname: "Smith",
    email: "jane.smith@gmail.com",
    // No password needed for social login
    password: "social_auth_token",
  };

  return (
    <Register>
      <Register.Header>
        <Register.Header.Title>Welcome, Jane!</Register.Header.Title>
        <Register.Header.Description>
          Your account has been created successfully
        </Register.Header.Description>
      </Register.Header>

      <Register.EmailForm
        defaultValues={socialUserData}
        tenantCode="your-tenant-code"
        onSuccess={(response) => {
          console.log("Social registration completed:", response);
          // Navigate to dashboard
        }}
        onError={(error) => console.error("Error:", error)}
      >
        {/* No input fields will be shown since all required data is provided */}
        <Register.EmailForm.Inputs />

        {/* Show completion message or additional setup options */}
        <View style={{ padding: 20, alignItems: "center" }}>
          <Text>Your account is ready to use!</Text>
        </View>

        <Register.EmailForm.RegisterButton />
      </Register.EmailForm>
    </Register>
  );
};
```

## Partial Data Flow [#partial-data-flow]

Handle cases where only some information is available:

```tsx
import React from "react";
import { Register } from "@ovok/native";

export const PartialDataRegistration = () => {
  // Email from invitation or previous step
  const partialData = {
    email: "invited.user@company.com",
  };

  return (
    <Register>
      <Register.Header>
        <Register.Header.Title>Complete Your Profile</Register.Header.Title>
        <Register.Header.Description>
          Please provide your details to finish registration
        </Register.Header.Description>
      </Register.Header>

      <Register.EmailForm
        defaultValues={partialData}
        tenantCode="your-tenant-code"
        onSuccess={(response) => console.log("Profile completed:", response)}
        onError={(error) => console.error("Error:", error)}
      >
        {/* Email field will be hidden, name/surname/password fields will show */}
        <Register.EmailForm.Inputs />
        <Register.EmailForm.RegisterButton />
      </Register.EmailForm>
    </Register>
  );
};
```

## Dynamic Data Loading [#dynamic-data-loading]

Load user data asynchronously and pre-fill the form:

```tsx
import React, { useState, useEffect } from "react";
import { Register } from "@ovok/native";
import { ActivityIndicator, View } from "react-native";

export const DynamicPreFilledRegistration = ({
  userId,
}: {
  userId: string;
}) => {
  const [userData, setUserData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadUserData = async () => {
      try {
        // Fetch user data from API
        const response = await fetch(`/api/users/${userId}/profile`);
        const data = await response.json();

        setUserData({
          name: data.firstName,
          surname: data.lastName,
          email: data.emailAddress,
        });
      } catch (error) {
        console.error("Failed to load user data:", error);
        setUserData({}); // Empty object to show all fields
      } finally {
        setLoading(false);
      }
    };

    loadUserData();
  }, [userId]);

  if (loading) {
    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        <ActivityIndicator size="large" />
      </View>
    );
  }

  return (
    <Register>
      <Register.Header>
        <Register.Header.Title>Update Your Information</Register.Header.Title>
        <Register.Header.Description>
          Please verify and complete your details
        </Register.Header.Description>
      </Register.Header>

      <Register.EmailForm
        defaultValues={userData}
        tenantCode="your-tenant-code"
        onSuccess={(response) => console.log("Updated successfully:", response)}
        onError={(error) => console.error("Update failed:", error)}
      >
        <Register.EmailForm.Inputs />
        <Register.EmailForm.RegisterButton />
      </Register.EmailForm>
    </Register>
  );
};
```

## Password-only Registration [#password-only-registration]

For cases where only password is needed:

```tsx
import React from "react";
import { Register } from "@ovok/native";

export const PasswordOnlyRegistration = () => {
  const completeUserData = {
    name: "Michael",
    surname: "Johnson",
    email: "michael.johnson@company.com",
  };

  return (
    <Register>
      <Register.Header>
        <Register.Header.Title>Set Your Password</Register.Header.Title>
        <Register.Header.Description>
          Create a secure password for your account: {completeUserData.email}
        </Register.Header.Description>
      </Register.Header>

      <Register.EmailForm
        defaultValues={completeUserData}
        tenantCode="your-tenant-code"
        onSuccess={(response) => console.log("Password set:", response)}
        onError={(error) => console.error("Error:", error)}
      >
        {/* Only password and password confirmation fields will show */}
        <Register.EmailForm.Inputs />
        <Register.EmailForm.Spacing percentage={2} />
        <Register.EmailForm.RegisterButton />
      </Register.EmailForm>
    </Register>
  );
};
```

## Editable Pre-filled Data [#editable-pre-filled-data]

Allow users to edit pre-filled information:

```tsx
import React, { useState } from "react";
import { Register } from "@ovok/native";
import { View, TouchableOpacity, Text } from "react-native";

export const EditablePreFilledRegistration = () => {
  const [allowEdit, setAllowEdit] = useState(false);

  const defaultData = {
    name: "Sarah",
    surname: "Wilson",
    email: "sarah.wilson@email.com",
  };

  // Don't pass defaultValues if editing is allowed
  const formDefaultValues = allowEdit ? {} : defaultData;

  return (
    <Register>
      <Register.Header>
        <Register.Header.Title>Confirm Your Details</Register.Header.Title>
        <Register.Header.Description>
          Review your information and set a password
        </Register.Header.Description>
      </Register.Header>

      {!allowEdit && (
        <View
          style={{ padding: 16, backgroundColor: "#F5F5F5", borderRadius: 8 }}
        >
          <Text style={{ fontSize: 16, marginBottom: 8 }}>
            Your Information:
          </Text>
          <Text>
            Name: {defaultData.name} {defaultData.surname}
          </Text>
          <Text>Email: {defaultData.email}</Text>

          <TouchableOpacity
            onPress={() => setAllowEdit(true)}
            style={{ marginTop: 12 }}
          >
            <Text style={{ color: "#007AFF", fontWeight: "600" }}>
              Edit Information
            </Text>
          </TouchableOpacity>
        </View>
      )}

      <Register.EmailForm
        defaultValues={formDefaultValues}
        tenantCode="your-tenant-code"
        onSuccess={(response) =>
          console.log("Registration completed:", response)
        }
        onError={(error) => console.error("Error:", error)}
      >
        <Register.EmailForm.Inputs />
        <Register.EmailForm.RegisterButton />
      </Register.EmailForm>
    </Register>
  );
};
```

## Form State Management [#form-state-management]

Handle complex pre-filled data scenarios:

```tsx
import React, { useMemo } from "react";
import { Register } from "@ovok/native";

interface UserProfile {
  firstName?: string;
  lastName?: string;
  emailAddress?: string;
  hasPassword?: boolean;
}

export const StateBasedRegistration = ({
  profile,
}: {
  profile: UserProfile;
}) => {
  const defaultValues = useMemo(() => {
    const values: any = {};

    if (profile.firstName) values.name = profile.firstName;
    if (profile.lastName) values.surname = profile.lastName;
    if (profile.emailAddress) values.email = profile.emailAddress;

    // If user already has a password, don't require password confirmation
    if (profile.hasPassword) {
      values.password = "existing_password";
      values.passwordConfirm = "existing_password";
    }

    return values;
  }, [profile]);

  const getHeaderContent = () => {
    const missingFields = [];
    if (!profile.firstName) missingFields.push("name");
    if (!profile.lastName) missingFields.push("surname");
    if (!profile.emailAddress) missingFields.push("email");
    if (!profile.hasPassword) missingFields.push("password");

    if (missingFields.length === 0) {
      return {
        title: "Welcome Back!",
        description: "Your account is ready to use.",
      };
    }

    return {
      title: "Complete Your Profile",
      description: `Please provide your ${missingFields.join(", ")} to continue.`,
    };
  };

  const headerContent = getHeaderContent();

  return (
    <Register>
      <Register.Header>
        <Register.Header.Title>{headerContent.title}</Register.Header.Title>
        <Register.Header.Description>
          {headerContent.description}
        </Register.Header.Description>
      </Register.Header>

      <Register.EmailForm
        defaultValues={defaultValues}
        tenantCode="your-tenant-code"
        onSuccess={(response) => console.log("Profile updated:", response)}
        onError={(error) => console.error("Error:", error)}
      >
        <Register.EmailForm.Inputs />
        <Register.EmailForm.RegisterButton />
      </Register.EmailForm>
    </Register>
  );
};
```

## Features [#features]

- **Conditional Fields**: Fields are automatically hidden when default values are provided
- **Flexible Data**: Support for partial, complete, or dynamic data
- **Social Integration**: Handle social login data seamlessly
- **State Management**: Complex logic for different user states
- **Validation**: Maintains validation rules even with pre-filled data
- **User Experience**: Smooth flow for different registration scenarios

## Field Visibility Rules [#field-visibility-rules]

| Default Value Provided          | Field Visibility             |
| ------------------------------- | ---------------------------- |
| `name`                          | Name field hidden            |
| `surname`                       | Surname field hidden         |
| `email`                         | Email field hidden           |
| `password`                      | Password field hidden        |
| `passwordConfirm` OR `password` | Password confirmation hidden |

## Best Practices [#best-practices]

1. **Clear Communication**: Tell users why fields are pre-filled
2. **Edit Options**: Allow users to modify pre-filled data when appropriate
3. **Validation**: Maintain proper validation even with default values
4. **Loading States**: Show loading indicators when fetching data
5. **Error Handling**: Handle cases where data loading fails
6. **Security**: Don't pre-fill sensitive data inappropriately

## Next Steps [#next-steps]

- [Basic Usage](/native-sdk/guide/components/auth/register/examples/basic-usage) - Learn fundamental registration patterns
- [Custom Validation](/native-sdk/guide/components/auth/register/examples/custom-validation) - Add validation for pre-filled data
