Skip to content

Commit

Permalink
chore: Code refactoring (#1482)
Browse files Browse the repository at this point in the history
* rename shouldRevalidate to revalidate

* bind event listeners

* refactor shouldDedupe condition

* fix conditions
  • Loading branch information
shuding authored Sep 22, 2021
1 parent 4f66f5a commit fb3d8b4
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 35 deletions.
50 changes: 28 additions & 22 deletions src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,11 @@ export const useSWRHandler = <Data = any, Error = any>(
let startAt: number
let loading = true
const opts = revalidateOpts || {}
const shouldDedupe = !isUndefined(CONCURRENT_PROMISES[key]) && opts.dedupe

// If there is no ongoing concurrent request, or `dedupe` is not set, a
// new request should be initiated.
const shouldStartNewRequest =
isUndefined(CONCURRENT_PROMISES[key]) || !opts.dedupe

// Do unmount check for callbacks:
// If key has changed during the revalidation, or the component has been
Expand All @@ -141,29 +145,23 @@ export const useSWRHandler = <Data = any, Error = any>(
delete CONCURRENT_PROMISES_TS[key]
}

// start fetching
// Start fetching. Change the `isValidating` state, update the cache.
cache.set(keyValidating, true)
setState({
isValidating: true
})

try {
cache.set(keyValidating, true)
setState({
isValidating: true
})
if (!shouldDedupe) {
// also update other hooks
if (shouldStartNewRequest) {
// Tell all other hooks to change the `isValidating` state.
broadcastState(
cache,
key,
stateRef.current.data,
stateRef.current.error,
true
)
}

if (shouldDedupe) {
// There's already an ongoing request, this one needs to be
// deduplicated.
startAt = CONCURRENT_PROMISES_TS[key]
newData = await CONCURRENT_PROMISES[key]
} else {
// If no cache being rendered currently (it shows a blank page),
// we trigger the loading slow event.
if (config.loadingTimeout && !cache.get(key)) {
Expand All @@ -174,18 +172,26 @@ export const useSWRHandler = <Data = any, Error = any>(
}

// Start the request and keep the timestamp.
CONCURRENT_PROMISES_TS[key] = startAt = getTimestamp()
newData = await (CONCURRENT_PROMISES[key] = fn.apply(fn, fnArgs))
CONCURRENT_PROMISES_TS[key] = getTimestamp()
CONCURRENT_PROMISES[key] = fn.apply(fn, fnArgs)
}

// Wait until the ongoing request is done. Deduplication is also
// considered here.
startAt = CONCURRENT_PROMISES_TS[key]
newData = await CONCURRENT_PROMISES[key]

if (shouldStartNewRequest) {
// If the request isn't interrupted, clean it up after the
// deduplication interval.
setTimeout(() => {
// CONCURRENT_PROMISES_TS[key] maybe be `undefined` or a number.
// CONCURRENT_PROMISES_TS[key] maybe be `undefined`.
if (CONCURRENT_PROMISES_TS[key] === startAt) {
cleanupState()
}
}, config.dedupingInterval)

// trigger the success event,
// only do this for the original request.
// Trigger the successful callback.
if (isCallbackSafe()) {
getConfig().onSuccess(newData, key, config)
}
Expand Down Expand Up @@ -251,7 +257,7 @@ export const useSWRHandler = <Data = any, Error = any>(
// merge the new state
setState(newState)

if (!shouldDedupe) {
if (shouldStartNewRequest) {
// also update other hooks
broadcastState(cache, key, newData, newState.error, false)
}
Expand All @@ -273,7 +279,7 @@ export const useSWRHandler = <Data = any, Error = any>(
isValidating: false,
error: err as Error
})
if (!shouldDedupe) {
if (shouldStartNewRequest) {
// Broadcast to update the states of other hooks.
broadcastState(cache, key, UNDEFINED, err, false)
}
Expand Down
4 changes: 2 additions & 2 deletions src/utils/broadcast-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const broadcastState: Broadcaster = (
data,
error,
isValidating,
shouldRevalidate = false
revalidate
) => {
const [EVENT_REVALIDATORS, STATE_UPDATERS] = SWRGlobalState.get(
cache
Expand All @@ -24,7 +24,7 @@ export const broadcastState: Broadcaster = (
}

// If we also need to revalidate, only do it for the first hook.
if (shouldRevalidate && revalidators && revalidators[0]) {
if (revalidate && revalidators && revalidators[0]) {
return revalidators[0](revalidateEvents.MUTATE_EVENT).then(() =>
cache.get(key)
)
Expand Down
6 changes: 3 additions & 3 deletions src/utils/mutate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const internalMutate = async <Data>(
cache: Cache,
_key: Key,
_data?: Data | Promise<Data | undefined> | MutatorCallback<Data>,
shouldRevalidate = true
revalidate = true
) => {
const [key, , keyErr] = serialize(_key)
if (!key) return
Expand All @@ -27,7 +27,7 @@ export const internalMutate = async <Data>(
cache.get(key),
cache.get(keyErr),
UNDEFINED,
shouldRevalidate
revalidate
)
}

Expand Down Expand Up @@ -86,7 +86,7 @@ export const internalMutate = async <Data>(
data,
error,
UNDEFINED,
shouldRevalidate
revalidate
)

// Throw error or return data
Expand Down
11 changes: 3 additions & 8 deletions src/utils/web-preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,13 @@ let online = true
const isOnline = () => online

// For node and React Native, `add/removeEventListener` doesn't exist on window.
const onWindowEvent = hasWindow
? (...args: Parameters<typeof window.addEventListener>) =>
window.addEventListener(...args)
: noop
const onWindowEvent = hasWindow ? window.addEventListener.bind(window) : noop
const onDocumentEvent = hasDocument
? (...args: Parameters<typeof document.addEventListener>) =>
document.addEventListener(...args)
? document.addEventListener.bind(document)
: noop
const offWindowEvent = (hasWindow && removeEventListener) || noop
const offDocumentEvent = hasDocument
? (...args: Parameters<typeof document.removeEventListener>) =>
document.removeEventListener(...args)
? document.removeEventListener.bind(document)
: noop

const isVisible = () => {
Expand Down

0 comments on commit fb3d8b4

Please sign in to comment.