Supposed that we want to observe real-time changes of a particular Firestore document, we could implement the logic in a custom hook and reuse the logic across many components:
export function useUserInfo() {
const [user, setUser] = useState<User | undefined>();
useEffect(() => {
const unsubscribe = subscribeFirestoreUser();
return () => unsubscribe();
}, []);
const subscribeFirestoreUser = () => {
const subscriber = firestore()
.collection(FIRESTORE_COLLECTIONS.USER)
.doc(userId) // an example id here
.onSnapshot(documentSnapshot => {
setUser(documentSnapshot.data() as User);
});
return subscriber;
};
return {
user,
};
}
To use the user information in other components:
export default function HomePage() {
const { user } = useUserInfo();
return <Text>{user.name}</Text>;
}
Top comments (0)