【问题标题】:Wait for async data from another mobx store等待来自另一个 mobx 存储的异步数据
【发布时间】:2017-08-01 10:20:28
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs firebase mobx


    【解决方案1】:

    我认为最简单的解决方案是在用户存储中保存对 firebase auth 承诺的引用,并在解决后使用 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();
        });
      }
    }
    

    【讨论】:

    • 哦,是的!谢谢!为什么我自己没有弄清楚:D
    猜你喜欢
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2022-06-29
    • 2020-11-23
    • 2015-09-07
    • 2018-08-23
    • 2021-06-16
    相关资源
    最近更新 更多