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.
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
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 }
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import React from 'react'
|
||||
import { render, waitFor } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import useLazyProfileCollections from './useLazyProfileCollections'
|
||||
|
||||
function Harness({ username = 'alice', initial = null, enabled = false }) {
|
||||
const state = useLazyProfileCollections({
|
||||
username,
|
||||
initialCollections: initial,
|
||||
enabled,
|
||||
})
|
||||
|
||||
return <output data-testid="state">{JSON.stringify(state)}</output>
|
||||
}
|
||||
|
||||
describe('useLazyProfileCollections', () => {
|
||||
beforeEach(() => vi.restoreAllMocks())
|
||||
|
||||
it('does not request while the profile remains on Posts', () => {
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch')
|
||||
render(<Harness />)
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requests once on first Collections activation and reuses the result', async () => {
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ data: [{ id: 1, title: 'One' }] }),
|
||||
})
|
||||
const view = render(<Harness />)
|
||||
|
||||
view.rerender(<Harness enabled />)
|
||||
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
|
||||
await waitFor(() => expect(JSON.parse(view.getByTestId('state').textContent).items).toHaveLength(1))
|
||||
|
||||
view.rerender(<Harness enabled={false} />)
|
||||
view.rerender(<Harness enabled />)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('treats an empty response as loaded and does not refetch', async () => {
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ data: [] }) })
|
||||
const view = render(<Harness enabled />)
|
||||
|
||||
await waitFor(() => expect(JSON.parse(view.getByTestId('state').textContent).loaded).toBe(true))
|
||||
view.rerender(<Harness enabled={false} />)
|
||||
view.rerender(<Harness enabled />)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('uses direct Collections SSR data without a lazy request', () => {
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch')
|
||||
const initial = [{ id: 9, title: 'SSR collection' }]
|
||||
const view = render(<Harness initial={initial} enabled />)
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
expect(JSON.parse(view.getByTestId('state').textContent).items).toEqual(initial)
|
||||
})
|
||||
|
||||
it('ignores a stale response after profile navigation', async () => {
|
||||
let resolveAlice
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockImplementation(() => new Promise((resolve) => { resolveAlice = resolve }))
|
||||
const view = render(<Harness username="alice" enabled />)
|
||||
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
|
||||
|
||||
view.rerender(<Harness username="bob" enabled />)
|
||||
resolveAlice({ ok: true, json: async () => ({ data: [{ id: 'alice' }] }) })
|
||||
await waitFor(() => expect(JSON.parse(view.getByTestId('state').textContent).items).toEqual([]))
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user