I'm working with an API that come with a pagination function but doesn't sort data based on the client's requirements. To work around this I'm fetching all data from the API inside getServerSideProps and only returning a portion of the data based on page number.
// getServerSideProps
export const getServerSideProps = (ctx) => {
ctx.res.setHeader(
'Cache-Control',
'public, s-maxage=60, stale-while-revalidate=120'
)
const page = ctx.query.page
const itemsPerPage = 6
const products = await getDataFromApi() //api sdk method
const featured = products.filter(isFeatured).sort(alphabetical)
const notFeatured = products.filter(isNotFeatured).sort(alphabetical)
const sortedProducts = [...featured, ...notFeatured]
return {
props : {
products : sortedProducts.slice(page - 1 * itemsPerPage, (page * itemsPerPage) + 1)
}
}
}
Edit: I used fetch as an example to simplify and make the code generic but irl, I'm actually using the api's sdk. I am also looking for any suggestions for a solution since I have been informed that this data may be in the thousands.
Does the cache control store all the data or only the ones returned after slicing? I want to reduce refetching if possible. The API sorting can only sort 1 field, I need to sort as such that featured products are shown in the first pages while sorted alphabetically within the featured block and non featured block respectively. Looking for a scalable solution as when the amount of data increases I'm concerned about load times and impacts on performance.
Thanks!
I've tried client-side fetching and sorting but I figured it's using the same logic so I moved it to server-side.
I've tried passing and storing all data on client-side in a state but I'm not sure on the load on the client side and performance impacts.
If you are using the fetch
api it caches by default everything you tried to fetch. Take a look at the documentation