refactor useAvatarETag
This commit is contained in:
parent
9c073fa6dc
commit
22230e0584
|
@ -1,5 +1,5 @@
|
|||
import { Q } from '@nozbe/watermelondb';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Observable, Subscription } from 'rxjs';
|
||||
|
||||
import { TSubscriptionModel, TUserModel } from '../../definitions';
|
||||
|
@ -16,50 +16,45 @@ export const useAvatarETag = ({
|
|||
text: string;
|
||||
rid?: string;
|
||||
}) => {
|
||||
const subscription = useRef<Subscription>();
|
||||
const [avatarETag, setAvatarETag] = useState<string | undefined>('');
|
||||
|
||||
const isDirect = () => type === 'd';
|
||||
|
||||
const unsubscribeQuery = () => {
|
||||
if (subscription?.current?.unsubscribe) {
|
||||
subscription.current.unsubscribe();
|
||||
}
|
||||
};
|
||||
|
||||
const init = async () => {
|
||||
unsubscribeQuery();
|
||||
const db = database.active;
|
||||
const usersCollection = db.get('users');
|
||||
const subsCollection = db.get('subscriptions');
|
||||
|
||||
let record;
|
||||
try {
|
||||
if (isDirect() || username === text) {
|
||||
const [user] = await usersCollection.query(Q.where('username', text)).fetch();
|
||||
record = user;
|
||||
} else if (rid) {
|
||||
record = await subsCollection.find(rid);
|
||||
}
|
||||
} catch {
|
||||
// Record not found
|
||||
}
|
||||
|
||||
if (record) {
|
||||
const observable = record.observe() as Observable<TSubscriptionModel | TUserModel>;
|
||||
subscription.current = observable.subscribe(r => {
|
||||
setAvatarETag(r.avatarETag);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let subscription: Subscription;
|
||||
if (!avatarETag) {
|
||||
init();
|
||||
(async () => {
|
||||
const db = database.active;
|
||||
const usersCollection = db.get('users');
|
||||
const subsCollection = db.get('subscriptions');
|
||||
|
||||
let record;
|
||||
try {
|
||||
if (isDirect() || username === text) {
|
||||
const [user] = await usersCollection.query(Q.where('username', text)).fetch();
|
||||
record = user;
|
||||
} else if (rid) {
|
||||
record = await subsCollection.find(rid);
|
||||
}
|
||||
} catch {
|
||||
// Record not found
|
||||
}
|
||||
|
||||
if (record) {
|
||||
const observable = record.observe() as Observable<TSubscriptionModel | TUserModel>;
|
||||
subscription = observable.subscribe(r => {
|
||||
setAvatarETag(r.avatarETag);
|
||||
});
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
if (subscription?.unsubscribe) {
|
||||
subscription.unsubscribe();
|
||||
}
|
||||
};
|
||||
}
|
||||
}, [text]);
|
||||
|
||||
useEffect(() => () => unsubscribeQuery(), []);
|
||||
|
||||
return { avatarETag };
|
||||
};
|
||||
|
|
Loading…
Reference in New Issue