等待来自另一个 mobx 存储的异步数据

Wait for async data from another mobx store

我有 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 仍然是 null。

这就是我合并商店的方式:

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 可观察对象何时可用?

我认为最简单的解决方案是在用户存储中保存对 firebase 身份验证承诺的引用,并在 TodoStore 解决后使用 currentUser

// 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();
    });
  }
}