question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

useSWRInfinite loses initialData

See original GitHub issue

Hi, with the deprecated useSWRPages I were able to set initialData (from my Next.js static props) and load only the next pages. I’d like to do the same with the new useSWRInfinite but if I set the initialData, this is lost after the next load; here an example:

https://codesandbox.io/s/swr-infinite-initial-data-00qk4

I tried also to set initialSize: 0 but with no luck :\

In the meantime I’m chaining the initialData with the result data

Thanks

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:10
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

4reactions
shudingcommented, Sep 6, 2021

initialData was renamed to fallbackData in SWR 1.0 to avoid confusion. With useSWRInfinite, if there’s no fetched result yet the fallback will be returned:

const { data } = useSWRInfinite(getKey, fetcher, { fallbackData: [1, 2, 3] })

It should return the following data when rendering:

[1, 2, 3] // still fetching, fallback returned
[page1] // fetched page 1

And when loading the next page,

[page1, page2]

There will not be a [page1, 2] state.

3reactions
koba04commented, Feb 9, 2021

According to https://github.com/vercel/swr/pull/894#issuecomment-759645838, it is expected that SWR doesn’t store initialData into the cache.

But I also understand that there are developers who expect that initialData is stored into the cache. The following is a test case that is based on #894, but it avoids sending a request for the first page. This returns initialData from the fetcher function if the request is for the first page.

  it('should re-use initialData and store it in the cache', async () => {
    const dummyResponses = {
      '/api?page=1': ['page-1-1', 'page-1-2'],
      '/api?page=2': ['page-2-1', 'page-2-2']
    }
    let requests = []
    const initialData = [dummyResponses[`/api?page=1`]]

    function Page() {
      const { data, size, setSize } = useSWRInfinite<string[], string>(
        index => {
          return [`page-test-11`, `/api?page=${index + 1}`]
        },
        async (_, index) => {
          const isInitialPage = index === `/api?page=1`;
          await new Promise(res => setTimeout(res, 100))
          if (isInitialPage) {
            return initialData[0]
          }
          requests.push(index)
          return dummyResponses[index]
        },
        {
          initialData,
        }
      )
      return (
        <div
          onClick={() => {
            // load next page
            setSize(size + 1)
          }}
        >
          {(data ? [].concat(...data) : []).join(', ')}
        </div>
      )
    }

    const { container } = render(<Page />)

    // render with the initialData
    expect(container.textContent).toMatchInlineSnapshot(`"page-1-1, page-1-2"`)
    expect(requests).toEqual([]) // should use the initial data
    fireEvent.click(container.firstElementChild)

    await screen.findByText('page-1-1, page-1-2, page-2-1, page-2-2')
    // The response for `page=1` should be reused from the cached data
    expect(requests).toEqual(['/api?page=2'])
  })

It would be nice if this is helpful for you.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to fix SWR to work correctly with initialData or fallbackData
I've been using the awesome data fetching library SWR (the same the same team behind Next.js, the React framework. SWR is a lightweight...
Read more >
useSWRInfiniteでinitialDataが認識されない現象が発生
ライブラリのアップデートは大事。 参考. useSWRInfinite loses initialData · Issue #588 · vercel/swr. Related #next.js. Next.
Read more >
API - SWR
SWR is a React Hooks library for data fetching. SWR first returns the data from cache (stale), then sends the fetch request (revalidate),...
Read more >
Useswr mutate - SPLIT FINGER
lost ark maxroll honing calculator ... initialData option the initial state. ... @shuding Is there a way to locally update useSWRInfinite data?
Read more >
Using SWR Bound Mutation Across Nextjs Pages with ...
Need help on using mutation with useSWRInfinite. EXPECTED. On my posts page, I used useSWRInfinite to do load posts with pagination. it ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found