Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useSWRInfinite loses initialData #588

Closed
valse opened this issue Aug 6, 2020 · 7 comments
Closed

useSWRInfinite loses initialData #588

valse opened this issue Aug 6, 2020 · 7 comments
Labels
area: pagination Pagination related issues bug Something isn't working

Comments

@valse
Copy link

valse commented Aug 6, 2020

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

@valse valse changed the title useSWRInfinite loses initialData useSWRInfinite loses initialData and scroll position on history back Aug 7, 2020
@valse valse changed the title useSWRInfinite loses initialData and scroll position on history back useSWRInfinite loses initialData Aug 7, 2020
@shuding shuding added bug Something isn't working area: pagination Pagination related issues labels Sep 20, 2020
@BenoitAverty
Copy link

I'm not sure that this is a bug.

One possible intention with the initialData option is to provide the data of the first page.

When you scroll, useSwrInfinite tries to revalidate the first page, and it replaces the initial data with the content of the first page (it assumes that the first page has changed)

I'm not sure this is intended or not, it would be great if a maintainer could tell us the intention behind this option.

@valse
Copy link
Author

valse commented Nov 4, 2020

On the previous 0.2.3 release it works as expected; in a SSR or SSG scenario the initial data I think that it was came from the server and the next pages will be the other one.

@doorman02
Copy link

Hi @valse @BenoitAverty @koba04 I am using useSWRInfinite with initialData set based on the first page data coming from SSR. However when I scroll down it reloads both page 1 and page 2. I would expect only page 2 to load.
Is it intentional behaviour to reload page 1 even if it is already set as initialData? Thanks!

@situplastik
Copy link

My "temporal solution" is put initialSize=0 as @valse initial propose, and initialData (as array declared) inside the concatenation array:

https://codesandbox.io/s/swr-infinite-initial-data-forked-ppo2r

With that, it works as expected, hope that helps more developers.

But would be great to admit initialData as we demand, as a simple array or and array with 1 position and the elements inside (following the return of the hook) simulating the first call. :)

@koba04
Copy link
Collaborator

koba04 commented Feb 9, 2021

According to #894 (comment), 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.

@shuding
Copy link
Member

shuding commented 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.

@moneszarrugh
Copy link

moneszarrugh commented Sep 19, 2023

I have an issue running swr v2.2.2 and next v11.1.0

const { data } = useSWRInfinite(getKey, undefined, {
    fallbackData: [fallbackData],
  });

console.log(fallbackData); // fallbackData returned from getStaticProps
console.log(data); // undefined when javascript is disabled

This issue is only with useSWRInfinite. useSWR works as expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area: pagination Pagination related issues bug Something isn't working
Projects
None yet
Development

No branches or pull requests

7 participants