With the global context and the Appwrite SDK ready, we can now implement the actual logic to create accounts and manage user sessions.
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:
ID.unique(): A utility from the Appwrite SDK that generates a unique string for the user's ID.account.create(): Sends the registration request to the backend.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;
}
};
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:
createEmailPasswordSession: The specific method to authenticate via email/password.account.get(): Fetches the currently authenticated user's details.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;
}
};
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)
}
};