Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWR not re-rendering when mutate is called

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>
    )
}
like image 433
Oddwerth Avatar asked Sep 05 '25 03:09

Oddwerth


1 Answers

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,
    },
)

Edit eager-darwin-qckch

like image 193
trixn Avatar answered Sep 07 '25 22:09

trixn