我可以将 'useSWR' 与 contentful-client 一起使用来创建分页吗?

Can I use 'useSWR' with the contentful-client to create pagination?

我正在尝试使用 nextjs 和 useSWR 挂钩创建分页。

这就是我目前的做法,它似乎在工作......但是我在文档中读到作为第一个参数传递的密钥应该是一个唯一的字符串(通常是 URL).我只是传递索引以获取正确的数据。我的方法会弄乱缓存吗?我不确定我这样做是否正确?

index.js

import React, { useState } from 'react'
import Page from '../components/page'

export default function IndexPage( ) {
  const [pageIndex, setPageIndex] = useState(0)

  return (
    <div>
      <Page index={pageIndex} />
      <button onClick={() => setPageIndex(pageIndex - 1)}>Previous</button>
      <button onClick={() => setPageIndex(pageIndex + 1)}>Next</button>
    </div>
  )
}

在我的 page.js

import useSWR from 'swr'
import { fetcher } from '../client/fetcher'

function Page({ index }) {
  const { data } = useSWR(index, fetcher)
  console.table(data)

  return <div>nothing here, just testing</div>

}

export default Page

最后 fetcher.js

import client from './contentful-client'

export async function fetcher(pageIndex = 1, limit = 3) {
  const data = await client.getEntries({
    content_type: 'posts',
    skip: pageIndex * limit,
    order: '-fields.publishDate',
    limit,
  })

  if (data) {
    return data
  }
  console.log('Something went wrong fetching data')
}

您可能希望将 Contentful 数据获取逻辑移至服务器,以免将凭据和逻辑暴露给浏览器。这可以使用 Next.js API routes.

来完成
// pages/api/posts.js

import client from '<path-to>/contentful-client' // Replace with appropriate path to file

export default async function handler(req, res) {
    const { pageIndex = 1, limit = 3 } = req.query
    const data = await client.getEntries({
        content_type: 'posts',
        skip: pageIndex * limit,
        order: '-fields.publishDate',
        limit,
    })

    res.json(data)
}

然后您可以重构页面中的代码以针对新创建的 API 路由发出请求,将路由 URL 作为键传递给 useSWR

import useSWR from 'swr'

const fetcher = (url) => fetch(url).then(res => res.json())

function Page({ index }) {
    const { data } = useSWR(`/api/posts?pageIndex=${index}`, fetcher)
    console.table(data)

    return <div>nothing here, just testing</div>
}

export default Page