Here are the notes for implementing the Logout functionality. These cover the logic in the global context and how to trigger it from a specific dashboard page.
In Appwrite, logging out means deleting the "session" stored on the server. We also need to clear our local state so the app knows there is no longer a logged-in user.
File Path: ./contexts/UserContext.jsx
// ... inside UserProvider
async function logout() {
try {
// 1. Delete the current active session from Appwrite
await account.deleteSession("current");
// 2. Clear the local global state
setUser(null);
} catch (error) {
console.log("Logout Error:", error.message);
throw error;
}
}
// Ensure logout is included in the Provider value
return (
<UserContext.Provider value={{ user, login, logout, register }}>
{children}
</UserContext.Provider>
);
We typically place the logout button on a settings or profile page. By using the useUser hook, we can access the logout function directly.
File Path: ./app/(dashboard)/profile.jsx
useUser to access global actions.ThemedButton to trigger the logout action.import { StyleSheet, Text } from "react-native";
import { useUser } from "../../hooks/useUser";
import ThemedView from "../../components/ThemedView";
import ThemedText from "../../components/ThemedText";
import ThemedButton from "../../components/ThemedButton";
const Profile = () => {
const { logout } = useUser(); // Grab logout from context
return (
<ThemedView style={styles.container}>
<ThemedText title={true}>Your Profile</ThemedText>
<ThemedButton onPress={logout}>
<Text style={{ color: "#F2F2F2" }}>Log Out</Text>
</ThemedButton>
</ThemedView>
);
};
export default Profile;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
});
It is important to understand that Appwrite considers a user "active" as long as a session exists.
"current").