useAddTopic Hook logic - abhiram-shaji/Langroove GitHub Wiki

Developer Documentation: useAddTopic Hook

This documentation outlines the implementation of the useAddTopic hook, which handles adding new topics to Firestore in a React Native Firebase application.


Overview

The useAddTopic hook:

  1. Manages the input for a topic description.
  2. Handles validation and error reporting for adding topics.
  3. Saves new topics to Firestore and navigates back to the previous screen after a successful addition.

Features and Functionality

1. State Management

Purpose

  • Manages the topic description input.

Implementation

  1. State Variables:

    • description: Stores the topic description entered by the user.
  2. Code Snippet:

    const [description, setDescription] = useState<string>('');
  3. Process:

    • The description state variable is updated using the setDescription method as the user types.

2. Input Validation

Purpose

  • Ensures the topic description is provided and the user is authenticated before saving.

Implementation

  1. Validation Steps:

    • Checks if the description is non-empty.
    • Ensures the user is logged in by verifying the presence of auth.currentUser.
  2. Code Snippet:

    if (!description) {
      Alert.alert('Error', 'Please enter a description');
      return;
    }
    
    const currentUser = auth.currentUser;
    
    if (!currentUser) {
      Alert.alert('Error', 'You must be logged in to add a topic');
      return;
    }
  3. Process:

    • Displays an alert for missing descriptions or unauthenticated users.
    • Prevents further execution if validation fails.

3. Saving to Firestore

Purpose

  • Saves the new topic to the Firestore topics collection with a unique ID.

Implementation

  1. Functionality:

    • Creates a topic document with fields:
      • description: The entered topic description.
      • ownerId: The UID of the current user.
      • ownerName: The display name of the current user or "Anonymous."
      • createdAt: A server-side timestamp.
  2. Code Snippet:

    const newTopic = {
      description,
      ownerId: currentUser.uid,
      ownerName: currentUser.displayName || 'Anonymous',
      createdAt: serverTimestamp(),
    };
    
    try {
      const topicDocRef = doc(db, 'topics', `${currentUser.uid}-${Date.now()}`);
      await setDoc(topicDocRef, newTopic);
      Alert.alert('Success', 'Topic added successfully');
      navigation.goBack();
    } catch (error) {
      console.error('Error saving topic:', error);
      Alert.alert('Error', 'Failed to save topic. Please try again.');
    }
  3. Process:

    • Generates a unique document ID using the user's UID and the current timestamp.
    • Saves the topic document using setDoc.

4. Navigation

Purpose

  • Navigates back to the previous screen (e.g., FeedScreen) after a successful topic addition.

Implementation

  1. Functionality:

    • Uses the navigation.goBack() method to return to the previous screen.
  2. Code Snippet:

    navigation.goBack();
  3. Process:

    • Triggered after a successful Firestore write operation.

Key Properties and Methods

Property/Method Description
description Stores the topic description entered by the user.
setDescription Updates the description state variable.
handleAddTopic Validates input, saves the topic to Firestore, and navigates back.

Error Handling

  • Input Errors:

    • Displays alerts if the description is missing or the user is not logged in.
  • Firestore Errors:

    • Logs errors and displays an alert if saving the topic to Firestore fails.

Notes

Firestore Document ID

  • The document ID is generated using the current user's UID and a timestamp to ensure uniqueness.

Default User Name

  • If the current user has no display name, the owner name defaults to "Anonymous."

For more details on Firebase Firestore methods, visit the Firebase Firestore Documentation. For React Navigation, refer to the React Navigation Documentation.

⚠️ **GitHub.com Fallback** ⚠️