我有2个商店:UserStore和TodoStore。 要获取待办事项,我需要知道我登录用户的ID。
这是我的UserStore的一部分
export default class UserStore {
@observable currentUser = null;
@observable loading = false;
constructor() {
this.subscribe();
}
@action subscribe = () => {
this.loading = true;
firebase.auth().onAuthStateChanged((user) => {
if(user) {
this.setCurrentUser(user);
} else {
this.unsetCurrentUser();
}
this.loading = false;
})
}
}
这是我的TodoStore的构造函数
constructor(users) {
this.users = users;
console.log(this.users.currentUser) //null
this.storageRef = firebase.storage().ref('files/todos');
this.todosRef = firebase.database().ref(`todos/${this.users.currentUser.uid}`);
this.filesRef = firebase.database().ref(`files/${this.users.currentUser.uid}/todos`);
this.logger();
}
这里的问题是我收到错误,因为在调用它时,currentUser仍为空。
这就是我将商店结合起来的方式:
const routing = new RouterStore();
const ui = new UiStore();
const users = new UserStore(ui);
const todos = new TodoStore(users);
const stores = {
routing,
ui,
users,
todos,
}
我做错了什么?我怎么知道currentUser observable何时可用?
答案 0 :(得分:4)
我认为最简单的解决方案是在用户存储中保存对firebase auth promise的引用,并在currentUser
解析后使用TodoStore
:
// UserStore.js
export default class UserStore {
@observable currentUser = null;
@observable loading = false;
authPromise = null;
constructor() {
this.subscribe();
}
@action subscribe = () => {
this.loading = true;
this.authPromise = firebase.auth().onAuthStateChanged((user) => {
if(user) {
this.currentUser = user;
} else {
this.currentUser = null;
}
this.loading = false;
})
}
}
// TodoStore.js
export default class TodoStore {
constructor(userStore) {
this.userStore = userStore;
userStore.authPromise.then(() => {
const uid = userStore.currentUser.uid;
this.storageRef = firebase.storage().ref('files/todos');
this.todosRef = firebase.database().ref(`todos/${uid}`);
this.filesRef = firebase.database().ref(`files/${uid}/todos`);
this.logger();
});
}
}