14- Registration and Login with Appwrite

With the global context and the Appwrite SDK ready, we can now implement the actual logic to create accounts and manage user sessions.

1. The Registration Flow

In Appwrite, "creating an account" and "logging in" are two separate steps. When a user registers, you create the account first, then manually trigger a login to create a session.

Inside ./context/userContext.jsx:

import { ID } from "react-native-appwrite";
import { account } from "../lib/appwrite";

const register = async (email, password) => {
  try {
    // 1. Create the user account
    await account.create(ID.unique(), email, password);
    
    // 2. Log them in immediately after registration
    await login(email, password);
  } catch (error) {
    console.log("Registration Error:", error.message);
    throw error;
  }
};

2. The Login Flow

To log a user in, we create a "Session." Once the session is created, we use account.get() to retrieve the full user object (containing their ID, email, etc.) and store it in our global state.

Inside userContext.jsx:

import { account } from "../lib/appwrite";

const login = async (email, password) => {
  try {
    // 1. Create the session (logs the user in on the server)
    await account.createEmailPasswordSession(email, password);
    
    // 2. Get user details and update global state
    const response = await account.get();
    setUser(response); 
  } catch (error) {
    console.log("Login Error:", error.message);
    throw error;
  }
};

3. Triggering from the UI

In your login.jsx or register.jsx pages, you use the useUser hook to call these functions. It is best practice to wrap these calls in a try...catch block to handle potential issues (like a password being too short or an email already existing).

Example in register.jsx: → ./app/(auth)/register.jsx

const { register } = useUser();

const handleSubmit = async () => {
  try {
    await register(email, password);
    // Success! The global 'user' state is now updated.
  } catch (err) {
    // Handle error (e.g., show an alert)
  }
};

4. Verifying the User State