I have 2 stores: UserStore and TodoStore. For fetching the todos i need to know the ID of my logged in user.
That's part of my 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;
})
}
}
and this is the constructor of my 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();
}
The problem here is that I am getting an error because at the moment of calling this the currentUser is still null.
This is how i combine my stores:
const routing = new RouterStore();
const ui = new UiStore();
const users = new UserStore(ui);
const todos = new TodoStore(users);
const stores = {
routing,
ui,
users,
todos,
}
What am I doing wrong? How do I know when the currentUser observable is available?
I think the easiest solution is this case would be to save a reference to the firebase auth promise in the user store, and use the currentUser in the TodoStore once it has resolved:
// 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();
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With