Untitled
unknown
typescript
4 years ago
2.1 kB
9
Indexable
import eb from '../../../eb';
import userModel from './UserModel';
export class UserEntity {
public userId;
public isSyncedWithDb = false;
public hasLoaded = false;
public exist = undefined;
public syncedOb = {};
public subscriptionCounts = 0;
constructor(userId: string) {
this.userId = userId;
}
public subscribe(){
this.subsctiptionCounts++;
this.subsctiptionCounts === 1 && this.unsubscribe = userModel.onUserSnapshot(this.userId, snapshot => {
if (!this.isSyncedWithDb) {
this.isSyncedWithDb = true;
}
if (!this.hasLoaded) {
this.hasLoaded = true;
}
this.exist = snapshot.exists;
if (snapshot.data()) {
this.syncedOb = snapshot.data()
}
});
}
public unsubscribe() {
this.subsctiptionCounts--;
try {
this.subsctiptionCounts === 0 && this.isSyncedWithDb = false;
this.subsctiptionCounts === 0 && this.unsubscribe();
} catch (error) {
}
}
public changeUserPassword = async (newPassword: string) => {
return userModel.changeUserPassword(this.userId, newPassword);
};
}
// Model
import functions from '@react-native-firebase/functions';
import firestore from '@react-native-firebase/firestore';
const UserModel = {
onUserSnapshot: (userId: string, callback: any) => {
return firestore().collection('Users').doc(userId).onSnapshot(callback);
},
changeUserPassword: (userId: string, newPassword: string) => {
return functions().httpsCallable('changeSelfpassword')({password: newPassword});
}
};
export default UserModel;
// Repository
import globalStore from './../globalStore';
const loadUser(userId: string) {
if(!globalStore.user){
const userEntity = proxy(new UserEntity(userId));
globalStore.user = userEntity;
}
}
// Global Store
import {proxy} from 'valtio';
export default proxy({});
// How I use that
useUser = ()=> {
const { user } = useSnapshot(globalStore);
useEffect(()=> {
loadUser(userId);
user.subscribe();
return () => user.unsubscribe();
})
return user
}
Editor is loading...