plane/apps/space/store/user.ts
sriram veeraghanta 8a95a41100
feat: Converting space app to pages dir (#2052)
Co-authored-by: Bavisetti Narayan <72156168+NarayanBavisetti@users.noreply.github.com>
Co-authored-by: NarayanBavisetti <narayan3119@gmail.com>
Co-authored-by: Bavisetti Narayan <narayan@Bavisettis-MacBook-Pro.local>
Co-authored-by: Nikhil <118773738+pablohashescobar@users.noreply.github.com>
Co-authored-by: M. Palanikannan <73993394+Palanikannan1437@users.noreply.github.com>
Co-authored-by: Lakhan Baheti <94619783+1akhanBaheti@users.noreply.github.com>
Co-authored-by: Dakshesh Jain <65905942+dakshesh14@users.noreply.github.com>
Co-authored-by: Aaryan Khandelwal <65252264+aaryan610@users.noreply.github.com>
2023-09-01 16:42:30 +05:30

76 lines
1.8 KiB
TypeScript

// mobx
import { observable, action, computed, makeObservable, runInAction } from "mobx";
// service
import UserService from "services/user.service";
export interface IUserStore {
currentUser: any | null;
fetchCurrentUser: () => void;
}
class UserStore implements IUserStore {
currentUser: any | null = null;
// root store
rootStore;
// service
userService;
constructor(_rootStore: any) {
makeObservable(this, {
// observable
currentUser: observable.ref,
// actions
setCurrentUser: action,
// computed
});
this.rootStore = _rootStore;
this.userService = new UserService();
}
setCurrentUser = (user: any) => {
// TODO: destructure user object
this.currentUser = user;
};
/**
*
* @param callback
* @description A wrapper function to check user authentication; it redirects to the login page if not authenticated, otherwise, it executes a callback.
* @example this.requiredLogin(() => { // do something });
*/
requiredLogin = (callback: () => void) => {
if (this.currentUser) {
callback();
return;
}
this.fetchCurrentUser()
.then(() => {
if (!this.currentUser) {
const currentPath = window.location.pathname;
window.location.href = `/?next_path=${currentPath}`;
} else callback();
})
.catch(() => {
const currentPath = window.location.pathname;
window.location.href = `/?next_path=${currentPath}`;
});
};
fetchCurrentUser = async () => {
try {
const response = await this.userService.currentUser();
if (response) {
runInAction(() => {
this.currentUser = response;
});
}
} catch (error) {
console.error("Failed to fetch current user", error);
}
};
}
export default UserStore;