I'm trying to create a product list with pagination using SWR and SSR. In order to do this, i'm passing initial data to SWR, and when pagination change, I call a mutate function, bounded to the first SWR request.
The problem is that the page isn't re-rendered, when I print the result of the mutate function, i see that the data has changed but the page just isn't re-rendered and i can't understand why.
Code :
const ProductList = ({initialData, endpoint, productLimit, productCount}) => {
const [pageIndex, setPageIndex] = useState(1)
const [isLoading, setIsLoading] = useState(false);
console.log(`${endpoint}?_limit=${productLimit}&_start=${pageIndex * productLimit ?? 0}`)
const {data, mutate} = useSWR(
`${endpoint}?_limit=${productLimit}&_start=${pageIndex * productLimit ?? 0}`,
fetcher,
{initialData: initialData}
)
return (
<div className={cls([styles.product_list_container])}>
<div>
<div className={cls([styles.product_list])}>
{data.map(product => {
return (
<ProductCard productData={product}/>
)
})}
</div>
<Pagination
pageIndex={pageIndex}
onclick={async (index) => {
setPageIndex(index);
setIsLoading(true)
mutate().then(resp => {
setIsLoading(false)
})
}}
pageNumber={Math.ceil(productCount / (productLimit) - 1)}/>
</div>
{isLoading &&
<LoadingBackdrop/>
}
</div>
)
}
When providing initialData
you also need to set revalidateOnMount: true
in the options or it will always only return the initial data:
const {data} = useSWR(
`${endpoint}?_limit=${productLimit}&_start=${pageIndex * productLimit ?? 0}`,
fetcher,
{
initialData: initialData,
revalidateOnMount: true,
},
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With