useProfileActions Hook Logic - abhiram-shaji/Langroove GitHub Wiki
useProfileActions
Hook
Developer Documentation: This documentation explains the useProfileActions
hook, which provides actions for interacting with a user's profile, such as adding friends and sending messages in a Firebase-authenticated React Native application.
Overview
The useProfileActions
hook:
- Enables users to send friend requests by updating the Firestore database.
- Facilitates navigation to a chat screen for messaging.
- Tracks loading states for friend addition actions.
Features and Functionality
1. Adding Friends
Purpose
- Allows the current user to add another user as a friend by updating both users' Firestore
friends
arrays.
Implementation
-
Functionality:
- Ensures the user is logged in before proceeding.
- Updates the
friends
array of both the current user and the friend in theusers
collection.
-
Code Snippet:
const handleAddFriend = async () => { if (!currentUser) return; // Ensure the user is logged in setLoading(true); try { const currentUserDocRef = doc(db, 'users', currentUser.uid); const ownerUserDocRef = doc(db, 'users', ownerId); await updateDoc(currentUserDocRef, { friends: arrayUnion(ownerId), }); await updateDoc(ownerUserDocRef, { friends: arrayUnion(currentUser.uid), }); Alert.alert('Success', 'You are now friends!'); } catch (error) { console.error('Error adding friend:', error); Alert.alert('Error', 'There was an error adding this user as a friend.'); } finally { setLoading(false); } };
-
Process:
- Retrieves references to both the current user's and friend's documents in Firestore.
- Uses
arrayUnion
to add the friend’sUID
to thefriends
array while avoiding duplicates. - Displays an alert on success or error.
2. Sending Messages
Purpose
- Navigates to a chat screen with a unique chat ID generated based on the current user and the profile owner's
UID
.
Implementation
-
Functionality:
- Checks if the user is logged in before proceeding.
- Creates a chat ID by sorting and concatenating the current user's and owner's
UIDs
. - Navigates to the
Chat
screen with the generatedchatId
.
-
Code Snippet:
const handleSendMessage = () => { console.log('Send Message pressed'); const currentUserId = currentUser?.uid; if (!currentUserId) { console.error('User not authenticated'); return; } const chatId = [currentUserId, ownerId].sort().join('_'); navigation.navigate('Chat', { chatId }); };
-
Process:
- Validates user authentication.
- Generates a deterministic chat ID to ensure consistency for the same pair of users.
- Passes the
chatId
to theChat
screen via navigation.
3. Loading State
Purpose
- Tracks the state of asynchronous operations, such as adding a friend.
Implementation
-
Functionality:
- Sets
loading
totrue
before starting an operation and resets it tofalse
when completed.
- Sets
-
Code Snippet:
const [loading, setLoading] = useState(false);
Key Properties and Methods
Property/Method | Description |
---|---|
handleAddFriend |
Adds the profile owner as a friend to the current user's friend list. |
handleSendMessage |
Navigates to the Chat screen with a unique chatId for messaging. |
loading |
Tracks whether the handleAddFriend operation is in progress. |
Usage Example
import React from 'react';
import { Button } from 'react-native';
import { useProfileActions } from './hooks/useProfileActions';
const ProfileScreen = ({ ownerId }: { ownerId: string }) => {
const { handleAddFriend, handleSendMessage, loading } = useProfileActions(ownerId);
return (
<>
<Button title="Add Friend" onPress={handleAddFriend} disabled={loading} />
<Button title="Send Message" onPress={handleSendMessage} />
</>
);
};
export default ProfileScreen;
Error Handling
-
Authentication Errors:
- Ensures the user is logged in before performing actions.
- Logs errors and displays alerts for unauthenticated users.
-
Firestore Errors:
- Logs errors and displays alerts if updating the
friends
array fails.
- Logs errors and displays alerts if updating the
Notes
-
Friendship Relationship:
- The
friends
array is updated bi-directionally, ensuring both users see each other as friends.
- The
-
Chat ID Generation:
- The chat ID is deterministic and consistent for a pair of users to avoid duplication.
For more details, refer to the Firebase Firestore Documentation and React Navigation Documentation.