I am trying to configure a login but having some trouble with async/await and getters/setters. I can't seem to set the user values before the getter for the values is called back in the Login component.
I have this basic login function:
private async login() {
await userModule.signIn({ username: this.username, password: this.pass })
const usr = await userModule.isSignedIn
console.log('Signed in:', usr) // comes back false
if(usr) {
this.goToDashboard()
} else {
alert('No user returned from user module')
this.resetLogin()
}
}
Calls this function in the userModule
@Action({ rawError: true })
public async signIn(userInfo: { username: string; password: string }) {
const { username, password } = userInfo;
// Login API called here and works fine
const { data } = await login("login", { username, password })
// This alert confirms the sign in was successful
alert(`Sign in from api -> ${JSON.stringify(data)}`)
// Trying to set the token and user here with async/await
await setToken(data.accessToken);
await setUser(JSON.stringify(data.user))
// This is the getter
const theUser = await this.isSignedIn
console.log('The User : ', theUser) // logs false
}
The setters are pretty straight forward:
@Mutation
private setUser(_user: User): void {
this.user = _user;
}
@Mutation
private setToken(_token: string) {
this.token = _token;
}
The getter part looks like this:
user = getUser();
token = getToken();
get isSignedIn() {
return this.user.email && this.token ? true : false;
}
Here are the corresponding getters and setters in the other module. They basically save and retrieve the values from session storage if they exist and return empty if they not.
export function setToken(token: string): void {
if (sessionStorage) {
sessionStorage.setItem(SESSION_TOKEN_KEY, token);
}
}
export function setUser(userData: string): void {
if (sessionStorage) {
sessionStorage.setItem(SESSION_USER_KEY, userData);
}
}
export function getToken(): string {
let token = "";
if (sessionStorage) {
const _token = sessionStorage.getItem(SESSION_TOKEN_KEY);
token = _token ? _token : token;
}
return token;
}
export function getUser(): User {
let user = {} as User;
if (sessionStorage) {
const userData = sessionStorage.getItem(SESSION_USER_KEY);
user = userData ? (JSON.parse(userData) as User) : ({} as User);
return user
}
return user;
}
I am pretty new to Typescript and finding it a bit difficult working with getters and setters, especially with async operations. That said, I think I am not using the setters correctly. If anyone can help me out with this I'd much appreciate it.