Files
road-monitoring-ui/src/store/auth.store.ts

41 lines
928 B
TypeScript

import { create } from 'zustand';
const ACCESS_TOKEN_KEY = 'access_token';
const getStoredAccessToken = () => {
if (typeof window === 'undefined') return null;
return localStorage.getItem(ACCESS_TOKEN_KEY);
};
interface AuthState {
accessToken: string | null;
isAuthenticated: boolean;
setAccessToken: (accessToken: string) => void;
logout: () => void;
}
export const useAuthStore = create<AuthState>()((set) => ({
accessToken: getStoredAccessToken(),
isAuthenticated: !!getStoredAccessToken(),
setAccessToken: (accessToken) => {
if (typeof window !== 'undefined') {
localStorage.setItem(ACCESS_TOKEN_KEY, accessToken);
}
set({
accessToken,
isAuthenticated: true,
});
},
logout: () => {
if (typeof window !== 'undefined') {
localStorage.removeItem(ACCESS_TOKEN_KEY);
}
set({
accessToken: null,
isAuthenticated: false,
});
},
}));