RefreshInterval在swr和next.js 13中不起作用。

huangapple go评论70阅读模式
英文:

RefreshInterval is not working in swr and next.js 13

问题

RefreshInterval 在 SWR 和 Next.js 中不起作用。

  • 我使用 Next.js 13 和 APP 文件夹
  • RefreshInterval 为 5000ms
  • 数据库是 Postgresql 和 ORM 是 Prisma

问题 - RefreshInterval 比 5000ms 快得多。
我可以在控制台看到数据在刷新(感觉每1毫秒加载一次数据),不久后我有数百次的重新加载,浏览器显示"Loading"(加载状态始终为 true),因为 RefreshInterval 不起作用?

有人知道问题是什么吗?

输出截图:console.log(data)

page.tsx

'使用客户端'
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>加载失败</div>
  if (isLoading) return <div className=""></div>Loading
  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('没有排行榜', { status: 404 })
    }

    return NextResponse.json(leaderboard)

  } catch (err) {
    return new NextResponse('出了些问题', { status: 400 })
  }
}
英文:

RefreshInterval in SWR and Next.js does not work.

  • I use Next.js 13 and the APP folder
  • RefreshInterval is 5000ms
  • Database Postgresql & ORM Prisma

Problem - the refreshInterval is a lot faster than 5000ms.
I can see the refreshing data in the console (feels like loading the data every 1ms) after a short time I have hundreds of reloads, and the browser shows "Loading" (loading state is true any time) because the RefreshInterval is not working?!

Does anyone know the problem?

Sreenshot output: console.log(data)

page.tsx

&#39;use client&#39;
import fetcher from &#39;@/lib/fetcher&#39;
import useSWR from &#39;swr&#39;

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 &lt;div&gt;failed to load&lt;/div&gt;
  if (isLoading) return &lt;div className=&quot;&quot;&gt;Loading&lt;/div&gt;
  console.log(data)
  
  return &lt;div&gt;{JSON.stringify(data)}&lt;/div&gt;

api/leaderboard/[id]/route.ts

import prisma from &#39;@/lib/prisma&#39;
import { NextResponse } from &#39;next/server&#39;

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: &#39;desc&#39;,
          },
        },
      },
    })
    if (!leaderboard) {
      return new NextResponse(&#39;No leaderboard&#39;, { status: 404 })
    }

    return NextResponse.json(leaderboard)

  } catch (err) {
    return new NextResponse(&#39;Something went wrong&#39;, { status: 400 })
  }
}

答案1

得分: 0

尝试从您的LeaderboardDetailPage中移除async

当前的Next.js版本中存在一个导致页面无限重新渲染的错误 - https://github.com/vercel/next.js/issues/49881

英文:

Try removing async from your LeaderboardDetailPage.

There is a bug in current Next.js version that's causing infinite page re-rerenders - https://github.com/vercel/next.js/issues/49881

答案2

得分: 0

错误的使用 useSWR 钩子位置:useSWR 钩子不应该在异步函数或被标记为 async 的组件内部使用。它应该直接在函数式组件内部使用。因此,您需要重构您的代码,从组件声明中移除 async 关键字。

SWR 文档:https://swr.vercel.app/

英文:

Incorrect placement of the useSWR hook: The useSWR hook should not be used inside an asynchronous function or a component marked as async. It should be used directly inside a functional component. Therefore, you need to refactor your code to remove the async keyword from the component declaration.

SWR Documentation: https://swr.vercel.app/

huangapple
  • 本文由 发表于 2023年5月25日 04:57:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76327354.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定