SWR和Next.js中的RefreshInterval不起作用。
- 我使用Next.js 13和APP文件夹
- RefreshInterval为5000 ms
- 数据库PostgreSQL & ORM Prisma
问题-refreshInterval比5000 ms快得多。我可以在控制台中看到刷新数据(感觉像每1 ms加载一次数据),在很短的时间内我有数百次重新加载后,浏览器显示“正在加载”(加载状态随时为真),因为RefreshInterval不工作?!
有谁知道这个问题吗?
Sreenshot output: console.log(data)
page.tsx
'use client'
import fetcher from '@/lib/fetcher'
import useSWR from 'swr'
export default async function LeaderboardDetailPage({ params }: { params: { id: string } }) {
const id = params.id
const { data, error, isLoading } = useSWR(`http://localhost:3000/api/leaderboards/${id}`, fetcher, { refreshInterval: 5000 })
if (error) return <div>failed to load</div>
if (isLoading) return <div className="">Loading</div>
console.log(data)
return <div>{JSON.stringify(data)}</div>
API/leaderboard/[id]/route.ts
import prisma from '@/lib/prisma'
import { NextResponse } from 'next/server'
export async function GET(request: Request, { params }: { params: { id: string } }) {
const id = params.id
try {
const leaderboard = await prisma.leaderboard.findUnique({
where: {
id: id,
},
select: {
id: true,
name: true,
backgroundUrl: true,
createdAt: true,
gameId: true,
game: {
select: {
id: true,
name: true,
},
},
scores: {
select: {
points: true,
player: {
select: {
id: true,
displayName: true,
},
},
},
orderBy: {
points: 'desc',
},
},
},
})
if (!leaderboard) {
return new NextResponse('No leaderboard', { status: 404 })
}
return NextResponse.json(leaderboard)
} catch (err) {
return new NextResponse('Something went wrong', { status: 400 })
}
}
2条答案
按热度按时间83qze16e1#
useSWR钩放置不正确:useSWR钩子不应该在异步函数或标记为async的组件中使用。它应该直接在功能组件内部使用。因此,您需要重构代码以从组件声明中删除async关键字。
SWR文档:https://swr.vercel.app/
uelo1irk2#
尝试从
LeaderboardDetailPage
中删除async
。当前Next.js版本中存在一个错误,导致无限页面重新呈现-https://github.com/vercel/next.js/issues/49881