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

enhance: provider release handlers #1449

Merged
merged 4 commits into from
Sep 11, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ export interface PublicConfiguration<
export type FullConfiguration = InternalConfiguration & PublicConfiguration

export type ConfigOptions = {
initFocus: (callback: () => void) => void
initReconnect: (callback: () => void) => void
initFocus: (callback: () => void) => (() => void) | void
initReconnect: (callback: () => void) => (() => void) | void
}

export type SWRHook = <Data = any, Error = any>(
Expand Down
2 changes: 1 addition & 1 deletion src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export const useSWRHandler = <Data = any, Error = any>(

// A revalidation must be triggered when mounted if:
// - `revalidateOnMount` is explicitly set to `true`.
// - `isPaused()` returns to `true`.
// - `isPaused()` returns `false`.
huozhi marked this conversation as resolved.
Show resolved Hide resolved
// - Suspense mode and there's stale data for the initial render.
// - Not suspense mode and there is no fallback data and `revalidateIfStale` is enabled.
// - `revalidateIfStale` is enabled but `data` is not defined.
Expand Down
15 changes: 9 additions & 6 deletions src/utils/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const revalidateAllKeys = (
export const initCache = <Data = any>(
provider: Cache<Data>,
options?: Partial<ConfigOptions>
): [Cache<Data>, ScopedMutator<Data>] | undefined => {
): [Cache<Data>, ScopedMutator<Data>, () => void] | undefined => {
// The global state for a specific provider will be used to deduplicate
// requests and store listeners. As well as a mutate function that bound to
// the cache.
Expand Down Expand Up @@ -55,28 +55,31 @@ export const initCache = <Data = any>(

// This is a new provider, we need to initialize it and setup DOM events
// listeners for `focus` and `reconnect` actions.
let unscubscibe = () => {}
if (!IS_SERVER) {
opts.initFocus(
const releaseFocus = opts.initFocus(
revalidateAllKeys.bind(
UNDEFINED,
EVENT_REVALIDATORS,
revalidateEvents.FOCUS_EVENT
)
)
opts.initReconnect(
const releaseReconnect = opts.initReconnect(
revalidateAllKeys.bind(
UNDEFINED,
EVENT_REVALIDATORS,
revalidateEvents.RECONNECT_EVENT
)
)
unscubscibe = () => {
releaseFocus && releaseFocus()
releaseReconnect && releaseReconnect()
}
}

// We might want to inject an extra layer on top of `provider` in the future,
// such as key serialization, auto GC, etc.
// For now, it's just a `Map` interface without any modifications.
return [provider, mutate]
return [provider, mutate, unscubscibe]
}

return
}
27 changes: 20 additions & 7 deletions src/utils/config-context.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { createContext, createElement, useContext, useState, FC } from 'react'

import {
createContext,
createElement,
useContext,
useState,
FC,
useEffect
} from 'react'
import { cache as defaultCache } from './config'
import { initCache } from './cache'
import { mergeConfigs } from './merge-config'
import { UNDEFINED } from './helper'
import { isFunction, UNDEFINED } from './helper'
import {
SWRConfiguration,
FullConfiguration,
Expand All @@ -26,18 +32,25 @@ const SWRConfig: FC<{
const provider = value && value.provider

// Use a lazy initialized state to create the cache on first access.
const [cacheAndMutate] = useState(() =>
const [cacheHandle] = useState(() =>
provider
? initCache(provider(extendedConfig.cache || defaultCache), value)
: UNDEFINED
)

// Override the cache if a new provider is given.
if (cacheAndMutate) {
extendedConfig.cache = cacheAndMutate[0]
extendedConfig.mutate = cacheAndMutate[1]
if (cacheHandle) {
extendedConfig.cache = cacheHandle[0]
extendedConfig.mutate = cacheHandle[1]
}

useEffect(() => {
return () => {
const unsubscribe = cacheHandle ? cacheHandle[2] : UNDEFINED
isFunction(unsubscribe) && unsubscribe()
}
}, [])

return createElement(
SWRConfigContext.Provider,
{ value: extendedConfig },
Expand Down
6 changes: 5 additions & 1 deletion src/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ const onErrorRetry = (
}

// Default cache provider
const [cache, mutate] = initCache(new Map()) as [Cache<any>, ScopedMutator<any>]
const [cache, mutate] = initCache(new Map()) as [
Cache<any>,
ScopedMutator<any>,
() => {}
]
export { cache, mutate }

// Default config
Expand Down
22 changes: 17 additions & 5 deletions src/utils/web-preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ const isOnline = () => online
// For node and React Native, `add/removeEventListener` doesn't exist on window.
const onWindowEvent = (hasWindow && addEventListener) || noop
const onDocumentEvent = (hasDocument && document.addEventListener) || noop
const offWindowEvent = (hasWindow && removeEventListener) || noop
const offDocumentEvent = (hasDocument && document.removeEventListener) || noop

const isVisible = () => {
const visibilityState = hasDocument && document.visibilityState
Expand All @@ -27,18 +29,28 @@ const initFocus = (cb: () => void) => {
// focus revalidate
onDocumentEvent('visibilitychange', cb)
onWindowEvent('focus', cb)
return () => {
offDocumentEvent('visibilitychange', cb)
offWindowEvent('focus', cb)
}
}

const initReconnect = (cb: () => void) => {
// reconnect revalidate
onWindowEvent('online', () => {
// revalidate on reconnected
const onOnline = () => {
online = true
cb()
})
}
// nothing to revalidate, just update the status
onWindowEvent('offline', () => {
const onOffline = () => {
online = false
})
}
onWindowEvent('online', onOnline)
onWindowEvent('offline', onOffline)
return () => {
offWindowEvent('online', onOnline)
offWindowEvent('offline', onOffline)
}
}

export const preset = {
Expand Down
9 changes: 8 additions & 1 deletion test/use-swr-cache.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ describe('useSWR - cache provider', () => {
it('should respect provider options', async () => {
const key = createKey()
const focusFn = jest.fn()
const unsubscribeFocusFn = jest.fn()
const unsubscribeReconnectFn = jest.fn()

let value = 1
function Foo() {
Expand All @@ -166,17 +168,19 @@ describe('useSWR - cache provider', () => {
provider: () => new Map([[key, 0]]),
initFocus() {
focusFn()
return unsubscribeFocusFn
},
initReconnect() {
/* do nothing */
return unsubscribeReconnectFn
}
}}
>
<Foo />
</SWRConfig>
)
}
render(<Page />)
const { unmount } = render(<Page />)
screen.getByText('0')

// mount
Expand All @@ -186,7 +190,10 @@ describe('useSWR - cache provider', () => {
await focusOn(window)
// revalidateOnFocus won't work
screen.getByText('1')
unmount()
expect(focusFn).toBeCalled()
expect(unsubscribeFocusFn).toBeCalledTimes(1)
expect(unsubscribeReconnectFn).toBeCalledTimes(1)
})

it('should work with revalidateOnFocus', async () => {
Expand Down
2 changes: 1 addition & 1 deletion test/use-swr-concurrent-rendering.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { createResponse, sleep } from './utils'
describe('useSWR - concurrent rendering', () => {
let React, ReactDOM, act, useSWR

beforeEach(() => {
beforeAll(() => {
jest.resetModules()
jest.mock('scheduler', () => require('scheduler/unstable_mock'))
jest.mock('react', () => require('react-experimental'))
Expand Down