如何解决我可以在 contentful-client 中使用“useSWR”来创建分页吗?
我正在尝试使用 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。