feat: add new composables for category, course, and authentication management.
This commit is contained in:
parent
fb4f345483
commit
8b403f906a
3 changed files with 59 additions and 12 deletions
|
|
@ -36,9 +36,22 @@ export const useCategory = () => {
|
|||
const API_BASE_URL = config.public.apiBase as string
|
||||
const { token } = useAuth()
|
||||
|
||||
// ใช้ useState เพื่อเก็บ Cached Data ระดับ Global (แชร์กันทุก Component)
|
||||
const categoriesState = useState<Category[]>('categories_cache', () => [])
|
||||
const isLoaded = useState<boolean>('categories_loaded', () => false)
|
||||
|
||||
// ฟังก์ชันดึงข้อมูลหมวดหมู่ทั้งหมด
|
||||
// Endpoint: GET /categories
|
||||
const fetchCategories = async () => {
|
||||
const fetchCategories = async (forceRefresh = false) => {
|
||||
// ถ้ามีข้อมูลอยู่แล้วและไม่สั่งบังคับโหลดใหม่ ให้ใช้ข้อมูลเดิมทันที
|
||||
if (isLoaded.value && !forceRefresh && categoriesState.value.length > 0) {
|
||||
return {
|
||||
success: true,
|
||||
data: categoriesState.value,
|
||||
total: categoriesState.value.length
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await $fetch<CategoryResponse>(`${API_BASE_URL}/categories`, {
|
||||
method: 'GET',
|
||||
|
|
@ -47,9 +60,15 @@ export const useCategory = () => {
|
|||
} : {}
|
||||
})
|
||||
|
||||
const categories = response.data?.categories || []
|
||||
|
||||
// เก็บข้อมูลลง State
|
||||
categoriesState.value = categories
|
||||
isLoaded.value = true
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data?.categories || [],
|
||||
data: categories,
|
||||
total: response.data?.total || 0
|
||||
}
|
||||
} catch (err: any) {
|
||||
|
|
@ -62,6 +81,7 @@ export const useCategory = () => {
|
|||
}
|
||||
|
||||
return {
|
||||
fetchCategories
|
||||
fetchCategories,
|
||||
categories: computed(() => categoriesState.value) // ส่งข้อมูลออกมาเป็น Computed เพื่อให้ UI อัปเดตตามอัตโนมัติ
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue