1
0
Fork 0
activist/src/stores/sessionStore.ts
2024-12-01 23:59:26 -05:00

66 lines
1.4 KiB
TypeScript

import {acceptHMRUpdate, defineStore} from 'pinia'
export interface User {
name: string,
sticker_ids: string[],
username: string | null,
}
const anonymous: User = {
name: 'Anonymous',
sticker_ids: [],
username: 'anonymous',
};
export interface State {
user: User,
}
export const useSessionStore = defineStore('session', {
actions: {
async login(username: string, password: string) {
const response = await fetch(
`/api/login`,
{
method: 'POST',
body: JSON.stringify({username, password}),
},
);
const json = await response.json();
console.log('login', json);
// this.user.name = json.name;
this.user = {
name: json.name,
sticker_ids: json.sticker_ids,
username: json.username,
};
},
logout() {
console.log('logout');
// TODO: Tell server.
this.user = anonymous;
// this.hasChanged = true;
// this.user.name = 'Anonymous';
// this.$reset();
// this.$patch({user: anonymous});
},
},
getters: {
initials: (state: State): string => {
return state.user.name[0] || '';
},
isAnonymous: (state: State): boolean => {
return state.user.username === 'anonymous';
},
},
state: (): State => {
return {
user: anonymous,
};
},
})
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useSessionStore, import.meta.hot))
}