diff --git a/src/hooks/useVulaContent.ts b/src/hooks/useVulaContent.ts new file mode 100644 index 0000000..f363e98 --- /dev/null +++ b/src/hooks/useVulaContent.ts @@ -0,0 +1,47 @@ +'use client' +import { useState, useEffect } from 'react' + +export interface CmsItem { + id: string + collection: string + title: string | null + data: Record + status: string + sortOrder: number + scheduledAt: string | null + expiresAt: string | null + publishedAt: string | null +} + +export function useVulaContent(collection: string) { + const [items, setItems] = useState([]) + const [loading, setLoading] = useState(true) + + useEffect(() => { + let controller = new AbortController() + + const fetchContent = () => { + controller = new AbortController() + fetch(`/api/content/${collection}`, { signal: controller.signal }) + .then(r => r.json()) + .then((data: { items?: CmsItem[] }) => { + setItems(data.items ?? []) + setLoading(false) + }) + .catch(err => { if (err?.name !== 'AbortError') setLoading(false) }) + } + + fetchContent() + const interval = setInterval(fetchContent, 30000) + const onVisible = () => { if (document.visibilityState === 'visible') fetchContent() } + document.addEventListener('visibilitychange', onVisible) + + return () => { + clearInterval(interval) + controller.abort() + document.removeEventListener('visibilitychange', onVisible) + } + }, [collection]) + + return { items, loading } +}