Skip to content

Commit

Permalink
fix: revalidate with initialData when changing the key
Browse files Browse the repository at this point in the history
  • Loading branch information
koba04 committed Feb 3, 2021
1 parent ef47355 commit dff1aa1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
2 changes: 2 additions & 0 deletions src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,7 @@ function useSWR<Data = any, Error = any>(
// after `key` updates, we need to mark it as mounted
unmountedRef.current = false

const isUpdating = initialMountedRef.current
initialMountedRef.current = true

// after the component is mounted (hydrated),
Expand All @@ -591,6 +592,7 @@ function useSWR<Data = any, Error = any>(

// trigger a revalidation
if (
isUpdating ||
config.revalidateOnMount ||
(!config.initialData && config.revalidateOnMount === undefined)
) {
Expand Down
32 changes: 30 additions & 2 deletions test/use-swr-integration.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { act, render, screen } from '@testing-library/react'
import React, { useEffect } from 'react'
import { act, render, screen, fireEvent } from '@testing-library/react'
import React, { useState, useEffect } from 'react'
import useSWR from '../src'
import { sleep } from './utils'

Expand Down Expand Up @@ -311,6 +311,34 @@ describe('useSWR', () => {
)
})

it('should revalidate even if initialData is provided', async () => {
const fetcher = key => key

function Page() {
const [key, setKey] = useState('initial-data-with-initial-data')
const { data } = useSWR(key, fetcher, {
initialData: 'Initial'
})
return (
<div onClick={() => setKey('initial-data-with-initial-data-update')}>
hello, {data}
</div>
)
}

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

// render with the initial data
await screen.findByText('hello, Initial')

// change the key
await act(() => sleep(1))
fireEvent.click(container.firstElementChild)

// render with data the fetcher returns
await screen.findByText('hello, initial-data-with-initial-data-update')
})

it('should set config as second parameter', async () => {
const fetcher = jest.fn(() => 'SWR')

Expand Down

0 comments on commit dff1aa1

Please sign in to comment.