These notes cover Error Handling in React Native when working with a backend like Appwrite, focusing on "throwing" errors from a global context and "catching" them in individual screens to update the UI.
When using a service like Appwrite, errors often happen inside your Context (logic layer). Instead of just logging them to the console, you must throw them so the UI component knows something went wrong.
UserContext.jsx./contexts/UserContext.jsx
Replace console.log(error) with throw error. This propagates the error up to the component that called the function.
async function register(email, password) {
try {
await account.create(ID.unique(), email, password);
await login(email, password);
} catch (error) {
// Throw the error so the Register screen can 'catch' it
throw error;
}
}
Each screen (Login/Register) needs its own local state to track if an error exists.
./app/(auth)/login.jsx (or ./app/(auth)/register.jsx)
null.null at the start of a new submission. This prevents old errors from "hanging" on the screen while a new request is processing.const [error, setError] = useState(null);
const handleSubmit = async () => {
setError(null); // Step 1: Reset before trying again
try {
await login(email, password);
} catch (err) {
setError(err.message); // Step 2: Capture the message
}
};
Use the short-circuit operator (&&) to show the error message only when the state is not null.
./app/(auth)/login.jsx