From dff1aa157ccc7860f2485a9335b666e2ae25303f Mon Sep 17 00:00:00 2001 From: Toru Kobayashi Date: Wed, 3 Feb 2021 23:32:52 +0900 Subject: [PATCH] fix: revalidate with initialData when changing the key --- src/use-swr.ts | 2 ++ test/use-swr-integration.test.tsx | 32 +++++++++++++++++++++++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/use-swr.ts b/src/use-swr.ts index 2bd4939976..6f7932fb39 100644 --- a/src/use-swr.ts +++ b/src/use-swr.ts @@ -569,6 +569,7 @@ function useSWR( // 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), @@ -591,6 +592,7 @@ function useSWR( // trigger a revalidation if ( + isUpdating || config.revalidateOnMount || (!config.initialData && config.revalidateOnMount === undefined) ) { diff --git a/test/use-swr-integration.test.tsx b/test/use-swr-integration.test.tsx index f6cd292b20..c38bb46b3a 100644 --- a/test/use-swr-integration.test.tsx +++ b/test/use-swr-integration.test.tsx @@ -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' @@ -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 ( +
setKey('initial-data-with-initial-data-update')}> + hello, {data} +
+ ) + } + + const { container } = render() + + // 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')