I am currently working on implementing pagination in a Next.js project using the useSWR hook. My approach seems to be functioning correctly, but I have a concern about caching due to the key parameter not being a unique string as recommended in the documentation.
Instead of passing a URL as the key, I am simply using the index to fetch the appropriate data. Will this affect the caching mechanism? I am unsure if I am following best practices here?
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>
)
}
And in my 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
And finally the 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')
}