【问题标题】:Can I use 'useSWR' with the contentful-client to create pagination?我可以将“useSWR”与内容客户端一起使用来创建分页吗?
【发布时间】:2021-03-14 18:00:15
【问题描述】:

我正在尝试使用 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')
}

【问题讨论】:

    标签: javascript caching next.js contentful swr


    【解决方案1】:

    您可能希望将 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
    

    【讨论】:

    • 感谢您的回答!我试过了,但访问 /api/posts 时出现 500 内部服务器错误。
    • 您知道具体是什么导致 API 路由出错吗?
    • 我很确定它是 client.getEntries()。
    • 没关系,我实际上是在寻找另一种 content_type.. 我改成了我真正拥有的 content_type,现在它可以工作了!
    • 你会说 useSWR 是这种目的的好选择吗? (分页和延迟加载)
    猜你喜欢
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2020-10-10
    相关资源
    最近更新 更多