0

I am using SWR package with Next JS. I am able to get the data using these and able to display that data in the table.

But now I want to show the load more type of pagination on the page of the listing. here below is my code:

Locations component:

import useSWR, { useSWRPages } from 'swr'
import axios from 'axios'
import { useState } from 'react'
//... other dependencies import

export default function Locations({...props}) {

    const [loading,setLoading] = useState(true)
    const [dataCount, setDataCount] = useState(3);
     const [pageIndex, setPageIndex] = useState(1)    

    const locationsFetcher = async() => {
        let response = await axios( process.env.url + '?page=${pageIndex}&limit=${dataCount}', headers:{})
        setLoading(false)
        let data = await response.data.results
        return data;
    }

    const {data, error} = useSWR('locations', locationsFetcher,{
        onErrorRetry: (error, key, config, revalidate, { retryCount }) => {
            if (error.status === 404) return
            if (retryCount >= 10) return
            
            setTimeout(() => revalidate({ retryCount }), 5000)
        }
    })

    const loadMore = () => {
        console.log("count " + dataCount +  " pageIndex " + pageIndex)
        setDataCount(dataCount + 3)
        setPageIndex(pageIndex + 1)
    }


    return (
        <>
            <table>
                {error && <tr><td><p>Error in Loading Data. </p></td></tr>}
                {(loading) ? <tr><td colSpan="6"><p>Loading ...</p></td></tr> : 
                (data && data.length > 0) ? (data.map((location, index) => (
                    <tr index={index} key={index}>
                        <td>{location.name}</td>
                         ...
                  
                        <td>{location.phone}</td>
                        </tr>
                ))) : (<tr><td><NoDataFound  /></td></tr>)}
                </table>
                <div className="click_btn">
                    <button onClick={() => loadMore()}>
                        <span>Expande Table</span>
                    </button>
                </div>
        </>


}

I am able to see the updated state value of the page and limit in the console log but unable to call API and display updated data on the listing.

Deep Kakkar
  • 5,831
  • 4
  • 39
  • 75

1 Answers1

1

As per https://swr.vercel.app/docs/pagination

You need to have the url as the first param in useSWR and you should also use ` instead of '.

const {data, error} = useSWR(process.env.url + `?page=${pageIndex}&limit=${dataCount}`, locationsFetcher,{
    onErrorRetry: (error, key, config, revalidate, { retryCount }) => {
        if (error.status === 404) return
        if (retryCount >= 10) return
        
        setTimeout(() => revalidate({ retryCount }), 5000)
    }
})