Skip to content

Commit

Permalink
Merge branch 'master' into passive
Browse files Browse the repository at this point in the history
  • Loading branch information
shuding committed Aug 16, 2021
2 parents 0467997 + 5276bae commit 8b712fd
Show file tree
Hide file tree
Showing 12 changed files with 69 additions and 59 deletions.
5 changes: 2 additions & 3 deletions examples/axios-typescript/libs/useRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export type GetRequest = AxiosRequestConfig | null
interface Return<Data, Error>
extends Pick<
SWRResponse<AxiosResponse<Data>, AxiosError<Error>>,
'isValidating' | 'revalidate' | 'error' | 'mutate'
'isValidating' | 'error' | 'mutate'
> {
data: Data | undefined
response: AxiosResponse<Data> | undefined
Expand All @@ -24,7 +24,7 @@ export default function useRequest<Data = unknown, Error = unknown>(
request: GetRequest,
{ initialData, ...config }: Config<Data, Error> = {}
): Return<Data, Error> {
const { data: response, error, isValidating, revalidate, mutate } = useSWR<
const { data: response, error, isValidating, mutate } = useSWR<
AxiosResponse<Data>,
AxiosError<Error>
>(
Expand Down Expand Up @@ -53,7 +53,6 @@ export default function useRequest<Data = unknown, Error = unknown>(
response,
error,
isValidating,
revalidate,
mutate
}
}
6 changes: 3 additions & 3 deletions examples/focus-revalidate/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { login, logout } from '../libs/auth'
import useSWR from 'swr'

export default () => {
const { data, revalidate } = useSWR('/api/user', fetch)
const { data, mutate } = useSWR('/api/user', fetch)

if (!data) return <h1>loading...</h1>
if (data.loggedIn) {
Expand All @@ -14,15 +14,15 @@ export default () => {
<img src={data.avatar} width={80} />
<Button onClick={() => {
logout()
revalidate() // after logging in/out, we revalidate the SWR
mutate() // after logging in/out, we mutate the SWR
}}>Logout</Button>
</div>
} else {
return <div>
<h1>Please login</h1>
<Button onClick={() => {
login()
revalidate()
mutate()
}}>Login</Button>
</div>
}
Expand Down
6 changes: 3 additions & 3 deletions examples/refetch-interval/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import fetch from '../libs/fetch'
import useSWR from 'swr'

export default () => {
const { data, revalidate } = useSWR('/api/data', fetch, {
const { data, mutate } = useSWR('/api/data', fetch, {
// revalidate the data per second
refreshInterval: 1000
})
Expand All @@ -21,7 +21,7 @@ export default () => {
ev.preventDefault()
setValue('')
await fetch(`/api/data?add=${value}`)
revalidate()
mutate()
}}>
<input placeholder='enter something' value={value} onChange={ev => setValue(ev.target.value)} />
</form>
Expand All @@ -30,7 +30,7 @@ export default () => {
</ul>
<Button onClick={async () => {
await fetch(`/api/data?clear=1`)
revalidate()
mutate()
}}>Clear All</Button>
</div>
)
Expand Down
13 changes: 4 additions & 9 deletions infinite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,15 @@ export const infinite = ((<Data, Error>(useSWRNext: SWRHook) => (
// - `mutate()` called
// - the cache is missing
// - it's the first page and it's not the initial render
// - cache has changed
// - cache for that page has changed
const shouldFetchPage =
revalidateAll ||
forceRevalidateAll ||
isUndefined(pageData) ||
(!i && !isUndefined(dataRef.current)) ||
(originalData && !config.compare(originalData[i], pageData))
(originalData &&
!isUndefined(originalData[i]) &&
!config.compare(originalData[i], pageData))

if (fn && shouldFetchPage) {
pageData = await fn(...pageArgs)
Expand Down Expand Up @@ -216,13 +218,6 @@ export const infinite = ((<Data, Error>(useSWRNext: SWRHook) => (
get: () => swr.data,
enumerable: true
},
// revalidate will be deprecated in the 1.x release
// because mutate() covers the same use case of revalidate().
// This remains only for backward compatibility
revalidate: {
get: () => swr.revalidate,
enumerable: true
},
isValidating: {
get: () => swr.isValidating,
enumerable: true
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "swr",
"version": "1.0.0-beta.9",
"version": "1.0.0-beta.10",
"description": "React Hooks library for remote data fetching",
"main": "./dist/index.js",
"module": "./dist/index.esm.js",
Expand Down
6 changes: 1 addition & 5 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export type Middleware = (useSWRNext: SWRHook) => SWRHookWithMiddleware
export type ValueKey = string | any[] | null

export type MutatorCallback<Data = any> = (
currentValue: undefined | Data
currentValue?: Data
) => Promise<undefined | Data> | undefined | Data

export type Broadcaster<Data = any, Error = any> = (
Expand Down Expand Up @@ -140,10 +140,6 @@ export type Key = ValueKey | (() => ValueKey)
export interface SWRResponse<Data, Error> {
data?: Data
error?: Error
/**
* @deprecated `revalidate` is deprecated, please use `mutate()` for the same purpose.
*/
revalidate: () => Promise<boolean>
mutate: KeyedMutator<Data>
isValidating: boolean
}
Expand Down
5 changes: 0 additions & 5 deletions src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -616,13 +616,8 @@ export const useSWRHandler = <Data = any, Error = any>(
throw isUndefined(error) ? revalidate({ dedupe: true }) : error
}

// Define the SWR state.
// `revalidate` will be deprecated in the 1.x release
// because `mutate()` covers the same use case of `revalidate()`.
// This remains only for backward compatibility
return Object.defineProperties(
{
revalidate,
mutate: boundMutate
},
{
Expand Down
10 changes: 5 additions & 5 deletions test/use-swr-config-callbacks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ describe('useSWR - config callbacks', () => {
let count = 0

function Page(props: { text: string }) {
const { data, revalidate } = useSWR(
const { data, mutate } = useSWR(
'config callbacks - onSuccess',
() => createResponse(count++),
{ onSuccess: () => (state = props.text) }
)
return (
<div onClick={revalidate}>
<div onClick={() => mutate()}>
hello, {data}, {props.text}
</div>
)
Expand Down Expand Up @@ -46,19 +46,19 @@ describe('useSWR - config callbacks', () => {
let count = 0

function Page(props: { text: string }) {
const { data, revalidate, error } = useSWR(
const { data, mutate, error } = useSWR(
'config callbacks - onError',
() => createResponse(new Error(`Error: ${count++}`)),
{ onError: () => (state = props.text) }
)
if (error)
return (
<div title={props.text} onClick={revalidate}>
<div title={props.text} onClick={() => mutate()}>
{error.message}
</div>
)
return (
<div onClick={revalidate}>
<div onClick={() => mutate()}>
hello, {data}, {props.text}
</div>
)
Expand Down
27 changes: 27 additions & 0 deletions test/use-swr-infinite.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -726,4 +726,31 @@ describe('useSWRInfinite', () => {
await act(() => sleep(1))
expect(renderedData).toEqual(['new'])
})

it('should reuse cached value for new pages', async () => {
const key = createKey()
const customCache = new Map([[key + '-1', 'cached value']])
const { cache } = createCache(customCache)

function Page() {
const { data, setSize } = useSWRInfinite<string, string>(
index => key + '-' + index,
() => createResponse('response value')
)
return (
<div onClick={() => setSize(2)}>data:{data ? data.join(',') : ''}</div>
)
}

render(
<SWRConfig value={{ cache }}>
<Page />
</SWRConfig>
)

screen.getByText('data:')
await screen.findByText('data:response value')
fireEvent.click(screen.getByText('data:response value'))
await screen.findByText('data:response value,cached value')
})
})
20 changes: 8 additions & 12 deletions test/use-swr-integration.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -187,22 +187,18 @@ describe('useSWR', () => {

it('should broadcast isValidating', async () => {
function useBroadcast3() {
const { isValidating, revalidate } = useSWR(
'broadcast-3',
() => sleep(100),
{
// need to turn of deduping otherwise
// revalidating will be ignored
dedupingInterval: 10
}
)
return { isValidating, revalidate }
const { isValidating, mutate } = useSWR('broadcast-3', () => sleep(100), {
// need to turn of deduping otherwise
// revalidating will be ignored
dedupingInterval: 10
})
return { isValidating, mutate }
}
function Initiator() {
const { isValidating, revalidate } = useBroadcast3()
const { isValidating, mutate } = useBroadcast3()
useEffect(() => {
const timeout = setTimeout(() => {
revalidate()
mutate()
}, 200)
return () => clearTimeout(timeout)
// the revalidate function is always the same reference because the key of the useSWR is static (broadcast-3)
Expand Down
22 changes: 12 additions & 10 deletions test/use-swr-revalidate.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ describe('useSWR - revalidate', () => {
let value = 0

function Page() {
const { data, revalidate } = useSWR('dynamic-3', () => value++)
return <button onClick={revalidate}>data: {data}</button>
const { data, mutate } = useSWR('dynamic-3', () => value++)
return <button onClick={() => mutate()}>data: {data}</button>
}

render(<Page />)
Expand All @@ -29,10 +29,10 @@ describe('useSWR - revalidate', () => {
let value = 0

function Page() {
const { data: v1, revalidate } = useSWR('dynamic-4', () => value++)
const { data: v1, mutate } = useSWR('dynamic-4', () => value++)
const { data: v2 } = useSWR('dynamic-4', () => value++)
return (
<button onClick={revalidate}>
<button onClick={() => mutate()}>
{v1}, {v2}
</button>
)
Expand All @@ -56,11 +56,11 @@ describe('useSWR - revalidate', () => {
let faster = false

function Page() {
const { data, revalidate } = useSWR('race', () =>
const { data, mutate } = useSWR('race', () =>
createResponse(faster ? 1 : 0, { delay: faster ? 50 : 100 })
)

return <button onClick={revalidate}>data: {data}</button>
return <button onClick={() => mutate()}>data: {data}</button>
}

render(<Page />)
Expand All @@ -83,14 +83,16 @@ describe('useSWR - revalidate', () => {

it('should keep isValidating be true when there are two concurrent requests', async () => {
function Page() {
const { isValidating, revalidate } = useSWR(
const { isValidating, mutate } = useSWR(
'keep isValidating for concurrent requests',
() => createResponse(null, { delay: 100 }),
{ revalidateOnMount: false }
)

return (
<button onClick={revalidate}>{isValidating ? 'true' : 'false'}</button>
<button onClick={() => mutate()}>
{isValidating ? 'true' : 'false'}
</button>
)
}

Expand All @@ -114,7 +116,7 @@ describe('useSWR - revalidate', () => {
it('should respect sequences of revalidation calls although in dedupingInterval', async () => {
let count = 0
function Page() {
const { data, revalidate } = useSWR(
const { data, mutate } = useSWR(
'respect sequences of revalidation calls although in dedupingInterval',
() => {
const currCount = ++count
Expand All @@ -124,7 +126,7 @@ describe('useSWR - revalidate', () => {
dedupingInterval: 30
}
)
return <div onClick={() => revalidate()}>count: {data}</div>
return <div onClick={() => mutate()}>count: {data}</div>
}

render(<Page />)
Expand Down
6 changes: 3 additions & 3 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5428,9 +5428,9 @@ path-key@^3.0.0, path-key@^3.1.0:
integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==

path-parse@^1.0.6:
version "1.0.6"
resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c"
integrity sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==
version "1.0.7"
resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735"
integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==

path-type@^4.0.0:
version "4.0.0"
Expand Down

0 comments on commit 8b712fd

Please sign in to comment.