Files
SkinbaseNova/resources/js/lib/useLazyProfileCollections.js
T
klevze 822b96e92a Lazy-load profile collections until the tab is opened.
Keep the profile payload smaller on first paint and fetch collections through a dedicated API when the collections tab is needed.
2026-09-20 14:49:33 +02:00

86 lines
2.6 KiB
JavaScript

import { useCallback, useEffect, useRef, useState } from 'react'
export default function useLazyProfileCollections({ username, initialCollections, enabled }) {
const hasInitialValue = Array.isArray(initialCollections)
const [items, setItems] = useState(() => hasInitialValue ? initialCollections : [])
const [loaded, setLoaded] = useState(hasInitialValue)
const [loading, setLoading] = useState(false)
const [error, setError] = useState(false)
const requestKeyRef = useRef(username)
const requestedRef = useRef(hasInitialValue)
const abortRef = useRef(null)
useEffect(() => {
if (requestKeyRef.current === username) return undefined
abortRef.current?.abort()
abortRef.current = null
requestKeyRef.current = username
requestedRef.current = false
setItems([])
setLoaded(false)
setLoading(false)
setError(false)
return undefined
}, [username])
useEffect(() => {
if (!hasInitialValue || requestKeyRef.current !== username) return undefined
abortRef.current?.abort()
abortRef.current = null
requestedRef.current = true
setItems(initialCollections)
setLoaded(true)
setLoading(false)
setError(false)
return undefined
}, [hasInitialValue, initialCollections, username])
const load = useCallback(async () => {
if (!enabled || hasInitialValue || requestKeyRef.current !== username || requestedRef.current || !username) return
requestedRef.current = true
const controller = new AbortController()
const requestKey = requestKeyRef.current
abortRef.current = controller
setLoading(true)
setError(false)
try {
const response = await fetch(`/api/profile/${encodeURIComponent(username)}/collections`, {
headers: { Accept: 'application/json' },
credentials: 'same-origin',
signal: controller.signal,
})
if (!response.ok) throw new Error('Collections could not be loaded.')
const payload = await response.json()
if (requestKey !== requestKeyRef.current || controller.signal.aborted) return
setItems(Array.isArray(payload?.data) ? payload.data : [])
setLoaded(true)
} catch (caught) {
if (caught?.name === 'AbortError' || requestKey !== requestKeyRef.current) return
requestedRef.current = false
setError(true)
} finally {
if (requestKey === requestKeyRef.current) {
abortRef.current = null
setLoading(false)
}
}
}, [enabled, hasInitialValue, username])
useEffect(() => {
if (enabled) load()
}, [enabled, load])
useEffect(() => () => abortRef.current?.abort(), [])
return { items, loaded, loading, error, retry: load }
}