Files
antrean-operasi/composables/useUserMenu.ts
2026-02-27 13:26:52 +07:00

75 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useUserMenuStore } from '~/store/userMenu'
export const useUserMenu = () => {
const menuStore = useUserMenuStore()
const { user } = useAuth()
const initializeMenu = async () => {
// Get token from localStorage (client-side only)
if (!process.client) {
return
}
// Skip if menu already fetched (even if empty/no access)
if (menuStore.menuFetched) {
console.log(' Menu already fetched, skipping re-fetch')
return
}
// Check if user ID is available
if (!user.value?.id) {
console.warn('⚠️ Cannot fetch menu: User ID not available')
return
}
const token = localStorage.getItem('idToken')
if (!token) {
console.warn('⚠️ Cannot fetch menu: No token available in localStorage')
return
}
// Use actual user ID from auth
const userIdToUse = user.value.id
try {
await menuStore.fetchUserMenu(userIdToUse, token)
} catch (error) {
console.error('❌ Error initializing menu:', error)
}
}
const refreshMenu = async () => {
if (!user.value?.id || !process.client) return
const token = localStorage.getItem('idToken')
if (!token) return
await menuStore.fetchUserMenu(user.value.id, token)
}
// Watch for user changes and auto-initialize menu
if (process.client) {
// Watch for user.id to become available
watchEffect(async () => {
const userId = user.value?.id
const hasToken = !!localStorage.getItem('idToken')
// Initialize if user ID and token exist, and menu not fetched yet
if (userId && hasToken && !menuStore.menuFetched && !menuStore.isLoading) {
await initializeMenu()
}
})
}
return {
menuStore,
menuItems: computed(() => menuStore.sidebarMenuItems),
hasMenu: computed(() => menuStore.hasMenu),
isLoading: computed(() => menuStore.isLoading),
error: computed(() => menuStore.error),
noAccess: computed(() => menuStore.noAccess),
initializeMenu,
refreshMenu
}
}