Feed Logic - abhiram-shaji/Langroove GitHub Wiki
Function:
This custom hook manages fetching and updating a list of topics from Firestore in real-time.
Example:
const { topics, handleTopicPress, loading } = useFeed();
This allows you to use the topics data and handle topic interactions in a component.
Function:
This hook manages the state of topics and loading status.
Example:
const [topics, setTopics] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
Here, topics
starts as an empty array, and loading
is initially true
while data is being fetched.
Function:
This hook is used to fetch data from Firestore when the component mounts.
Example:
useEffect(() => {
const topicsCollection = collection(db, 'topics');
// Code to set up real-time listener
}, []); // Empty array means this runs once
This runs once when the component mounts to set up a listener for the topics collection.
Function:
This method listens for real-time updates to the specified Firestore collection.
Example:
const unsubscribe = onSnapshot(topicsCollection, (snapshot) => {
const topicsData = snapshot.docs.map(doc => ({
id: doc.id,
...doc.data(),
}));
setTopics(topicsData);
setLoading(false);
}, (error) => {
console.error('Error fetching real-time topics:', error);
setLoading(false);
});
This listens for changes in the topics
collection and updates the topics
state whenever changes occur.
Function:
This part ensures the real-time listener is removed when the component unmounts to prevent memory leaks.
Example:
return () => unsubscribe();
This line returns a function that will unsubscribe from the Firestore listener when the component is no longer in use.
Function:
This function can be used to handle interactions when a topic is pressed.
Example:
const handleTopicPress = (description: string) => {
console.log(`Tapped on ${description}`);
};
This logs a message when a topic is tapped, which you can expand to perform other actions.