List of Friends Logic - abhiram-shaji/Langroove GitHub Wiki
Function:
This custom hook manages fetching and filtering a user's friend list from Firestore.
Example:
const { search, setSearch, filteredFriends } = useFriendList();
This allows you to access the friend list, search functionality, and filtered results in a component.
Function:
This hook manages the state of friends and the search term.
Example:
const [friends, setFriends] = useState<Friend[]>([]);
const [search, setSearch] = useState<string>('');
Here, friends
starts as an empty array, and search
is an empty string for searching friends.
Function:
This retrieves the currently logged-in user using Firebase Authentication.
Example:
const currentUser = auth.currentUser;
This gets the current user object, which is used to fetch that user’s friends.
Function:
This hook fetches the friends list when the component mounts and whenever the current user changes.
Example:
useEffect(() => {
if (currentUser) {
fetchFriends();
}
}, [currentUser]);
When currentUser
is available, it calls the fetchFriends
function to load friends from Firestore.
Function:
This function retrieves the logged-in user’s friends list from Firestore.
Example:
const fetchFriends = async () => {
if (!currentUser) return;
// Fetching logic here
};
It checks if the user is logged in, then fetches their document and friend IDs.
Function:
This fetches details for each friend using their IDs stored in the current user’s document.
Example:
const friendsPromises = friendsIds.map(async (friendId: string) => {
const friendDocRef = doc(db, 'users', friendId);
const friendDoc = await getDoc(friendDocRef);
// Extract friend data
});
It maps over the friend IDs to create a promise for fetching each friend's data.
Function:
After fetching friend data, this updates the friends
state with the retrieved details.
Example:
setFriends(friendsData); // Update state with fetched friends
This sets the friends
state to the list of friends retrieved from Firestore.
Function:
This filters the friends list based on the current search term.
Example:
const filteredFriends = friends.filter((friend) =>
friend.name.toLowerCase().includes(search.toLowerCase())
);
This creates a new array of friends that match the search term (case-insensitive).