Sign Up Logic - abhiram-shaji/Langroove GitHub Wiki
useSignUp
Hook
1. Function:
This custom hook handles user registration (sign-up) using Firebase.
Example:
const { credentials, error, loading, handleInputChange, handleSignUp } = useSignUp();
This allows you to manage sign-up logic and states in a functional component.
useState
2. State Management with Function:
This hook is used to manage the state of user credentials, errors, and loading status.
Example:
const [credentials, setCredentials] = useState<Credentials>({
name: '',
email: '',
password: '',
confirmPassword: '',
});
Here, credentials
holds the user's input, and it starts with empty fields.
handleInputChange
Function
3. Function:
This function updates the state for each input field (name, email, password, confirmPassword).
Example:
const handleInputChange = (field: keyof Credentials, value: string) => {
setCredentials({ ...credentials, [field]: value });
};
When you change an input field, this function updates the corresponding value in credentials
.
handleSignUp
Function
4. Function:
This function handles the sign-up process, including validation and Firebase authentication.
Example:
const handleSignUp = async () => {
// Code for sign-up logic
};
This function performs multiple tasks:
- Validates the input fields.
- Creates a user in Firebase using their email and password.
- Updates the user’s profile with their name.
- Stores user information (like avatar) in Firestore.
- Navigates to the Login screen after successful sign-up.
5. Validation Checks
Function:
Before proceeding with sign-up, the function checks for:
- Empty fields
- Password match
Example:
if (!name || !email || !password || !confirmPassword) {
setError('Please fill out all fields.');
return;
}
if (password !== confirmPassword) {
setError('Passwords do not match.');
return;
}
These checks ensure that the user has provided valid input before proceeding.
6. Firebase User Creation
Function:
This part of the code creates a user in Firebase Authentication.
Example:
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
This line attempts to register the user with the provided email and password.
7. Updating User Profile
Function:
After creating a user, this updates their profile with their display name.
Example:
await updateProfile(userCredential.user, { displayName: name });
This assigns the user's name as their display name in Firebase.
8. Storing User Data in Firestore
Function:
After signing up, user details are saved in Firestore.
Example:
await setDoc(doc(db, 'users', uid), {
name,
email,
avatar: avatarUrl,
});
This saves the user's name, email, and a generated avatar URL in the Firestore database.
9. Error Handling
Function:
If any error occurs during sign-up, it is caught and displayed.
Example:
} catch (error: any) {
setError(error.message);
}
This line sets the error state to show any issues encountered during the sign-up process.