useProfileActions Hook Logic - abhiram-shaji/Langroove GitHub Wiki

Developer Documentation: useProfileActions Hook

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:

  1. Enables users to send friend requests by updating the Firestore database.
  2. Facilitates navigation to a chat screen for messaging.
  3. 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

  1. Functionality:

    • Ensures the user is logged in before proceeding.
    • Updates the friends array of both the current user and the friend in the users collection.
  2. 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);
      }
    };
    
  3. Process:

    • Retrieves references to both the current user's and friend's documents in Firestore.
    • Uses arrayUnion to add the friend’s UID to the friends 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

  1. 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 generated chatId.
  2. 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 });
    };
    
  3. Process:

    • Validates user authentication.
    • Generates a deterministic chat ID to ensure consistency for the same pair of users.
    • Passes the chatId to the Chat screen via navigation.

3. Loading State

Purpose

  • Tracks the state of asynchronous operations, such as adding a friend.

Implementation

  1. Functionality:

    • Sets loading to true before starting an operation and resets it to false when completed.
  2. 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.

Notes

  • Friendship Relationship:

    • The friends array is updated bi-directionally, ensuring both users see each other as friends.
  • 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.