0

I have a load more button, within a brand new Next.js app, that uses useSWRInfinite. Every time I click it it makes 2 calls to my backend. The first call is with index 0 and the second is with the incremented index.

Here is my component:

function Home() {
  const { data, size, setSize } = useSWRInfinite(
    (index) => `/api/user?page=${index}&per_page=2`,
    (url) => fetch(url).then((r) => r.json()),
    { initialSize: 1 }
  )
  return <button onClick={() => setSize(size + 1)}>{'load more'}</button>
}

And here is my endpoint

export default (req, res) => {
  console.log('calling the backend with', req.query)
  res.send(200)
}

These are the logs after I've clicked the button 3 times:

calling the backend with { page: '0', per_page: '2' }
calling the backend with { page: '1', per_page: '2' }
calling the backend with { page: '0', per_page: '2' }
calling the backend with { page: '2', per_page: '2' }
calling the backend with { page: '0', per_page: '2' }
calling the backend with { page: '3', per_page: '2' }

Why does it call the backend with page / index 0 and then again with the correct incremented index?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
grabury
  • 4,797
  • 14
  • 67
  • 125

2 Answers2

7

Its a feature given in useSWRInfinite to validate first page before the call of every next page. post 1.1.0 version you can disable by setting

revalidateFirstPage : false

https://github.com/vercel/swr/releases/tag/1.1.0

  const { data, size, setSize } = useSWRInfinite(
    (index) => `/api/user?page=${index}&per_page=2`,
    (url) => fetch(url).then((r) => r.json()),
    { 
      initialSize: 1, 
      revalidateFirstPage : false 
    }
  )
  return <button onClick={() => setSize(size + 1)}>{'load more'}</button>
}
Tech-reTech
  • 89
  • 1
  • 3
1

I think in swr.vercel.app (link to documentation) did mentioned about the response being a multiple one as shown below.

enter image description here

Maybe if you could specify in your getKey function that you just want to make one request (which I think defeat the purposes of using the useSWRInfinite - for pagination) like shown below:-

enter image description here

lala
  • 1,309
  • 9
  • 21