Comparing version 2.2.6-beta.4 to 2.2.6-beta.5
Object.defineProperty(exports, '__esModule', { value: true }); | ||
var configContextClient = require('./config-context-client-C7E1GYsL.js'); | ||
var configContextClient = require('./config-context-client-CTAS8iBI.js'); | ||
var React = require('react'); | ||
@@ -5,0 +5,0 @@ |
@@ -1,6 +0,7 @@ | ||
import { Middleware, SWRHook } from '../_internal/index.js'; | ||
import * as ___index from '../index/index.js'; | ||
import { Middleware } from '../index/index.js'; | ||
declare const immutable: Middleware; | ||
declare const useSWRImmutable: SWRHook; | ||
declare const useSWRImmutable: ___index.SWRHook; | ||
export { useSWRImmutable as default, immutable }; |
Object.defineProperty(exports, '__esModule', { value: true }); | ||
var React = require('react'); | ||
var index_js = require('use-sync-external-store/shim/index.js'); | ||
var _internal = require('swr/_internal'); | ||
var useSWR = require('../index/index.js'); | ||
var index_js = require('../_internal/index.js'); | ||
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } | ||
var React__default = /*#__PURE__*/_interopDefault(React); | ||
var useSWR__default = /*#__PURE__*/_interopDefault(useSWR); | ||
/// <reference types="react/experimental" /> | ||
const use = React__default.default.use || // This extra generic is to avoid TypeScript mixing up the generic and JSX sytax | ||
// and emitting an error. | ||
// We assume that this is only for the `use(thenable)` case, not `use(context)`. | ||
// https://github.com/facebook/react/blob/aed00dacfb79d17c53218404c52b1c7aa59c4a89/packages/react-server/src/ReactFizzThenable.js#L45 | ||
((thenable)=>{ | ||
switch(thenable.status){ | ||
case 'pending': | ||
throw thenable; | ||
case 'fulfilled': | ||
return thenable.value; | ||
case 'rejected': | ||
throw thenable.reason; | ||
default: | ||
thenable.status = 'pending'; | ||
thenable.then((v)=>{ | ||
thenable.status = 'fulfilled'; | ||
thenable.value = v; | ||
}, (e)=>{ | ||
thenable.status = 'rejected'; | ||
thenable.reason = e; | ||
}); | ||
throw thenable; | ||
} | ||
}); | ||
const WITH_DEDUPE = { | ||
dedupe: true | ||
}; | ||
const useSWRHandler = (_key, fetcher, config)=>{ | ||
const { cache, compare, suspense, fallbackData, revalidateOnMount, revalidateIfStale, refreshInterval, refreshWhenHidden, refreshWhenOffline, keepPreviousData } = config; | ||
const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = _internal.SWRGlobalState.get(cache); | ||
// `key` is the identifier of the SWR internal state, | ||
// `fnArg` is the argument/arguments parsed from the key, which will be passed | ||
// to the fetcher. | ||
// All of them are derived from `_key`. | ||
const [key, fnArg] = _internal.serialize(_key); | ||
// If it's the initial render of this hook. | ||
const initialMountedRef = React.useRef(false); | ||
// If the hook is unmounted already. This will be used to prevent some effects | ||
// to be called after unmounting. | ||
const unmountedRef = React.useRef(false); | ||
// Refs to keep the key and config. | ||
const keyRef = React.useRef(key); | ||
const fetcherRef = React.useRef(fetcher); | ||
const configRef = React.useRef(config); | ||
const getConfig = ()=>configRef.current; | ||
const isActive = ()=>getConfig().isVisible() && getConfig().isOnline(); | ||
const [getCache, setCache, subscribeCache, getInitialCache] = _internal.createCacheHelper(cache, key); | ||
const stateDependencies = React.useRef({}).current; | ||
// Resolve the fallback data from either the inline option, or the global provider. | ||
// If it's a promise, we simply let React suspend and resolve it for us. | ||
let fallback = _internal.isUndefined(fallbackData) ? _internal.isUndefined(config.fallback) ? _internal.UNDEFINED : config.fallback[key] : fallbackData; | ||
if (fallback && _internal.isPromiseLike(fallback)) { | ||
fallback = use(fallback); | ||
} | ||
const isEqual = (prev, current)=>{ | ||
for(const _ in stateDependencies){ | ||
const t = _; | ||
if (t === 'data') { | ||
if (!compare(prev[t], current[t])) { | ||
if (!_internal.isUndefined(prev[t])) { | ||
return false; | ||
} | ||
if (!compare(returnedData, current[t])) { | ||
return false; | ||
} | ||
} | ||
} else { | ||
if (current[t] !== prev[t]) { | ||
return false; | ||
} | ||
} | ||
} | ||
return true; | ||
}; | ||
const getSnapshot = React.useMemo(()=>{ | ||
const shouldStartRequest = (()=>{ | ||
if (!key) return false; | ||
if (!fetcher) return false; | ||
// If `revalidateOnMount` is set, we take the value directly. | ||
if (!_internal.isUndefined(revalidateOnMount)) return revalidateOnMount; | ||
// If it's paused, we skip revalidation. | ||
if (getConfig().isPaused()) return false; | ||
if (suspense) return false; | ||
return revalidateIfStale !== false; | ||
})(); | ||
// Get the cache and merge it with expected states. | ||
const getSelectedCache = (state)=>{ | ||
// We only select the needed fields from the state. | ||
const snapshot = _internal.mergeObjects(state); | ||
delete snapshot._k; | ||
if (!shouldStartRequest) { | ||
return snapshot; | ||
} | ||
return { | ||
isValidating: true, | ||
isLoading: true, | ||
...snapshot | ||
}; | ||
}; | ||
const cachedData = getCache(); | ||
const initialData = getInitialCache(); | ||
const clientSnapshot = getSelectedCache(cachedData); | ||
const serverSnapshot = cachedData === initialData ? clientSnapshot : getSelectedCache(initialData); | ||
// To make sure that we are returning the same object reference to avoid | ||
// unnecessary re-renders, we keep the previous snapshot and use deep | ||
// comparison to check if we need to return a new one. | ||
let memorizedSnapshot = clientSnapshot; | ||
return [ | ||
()=>{ | ||
const newSnapshot = getSelectedCache(getCache()); | ||
const compareResult = isEqual(newSnapshot, memorizedSnapshot); | ||
if (compareResult) { | ||
// Mentally, we should always return the `memorizedSnapshot` here | ||
// as there's no change between the new and old snapshots. | ||
// However, since the `isEqual` function only compares selected fields, | ||
// the values of the unselected fields might be changed. That's | ||
// simply because we didn't track them. | ||
// To support the case in https://github.com/vercel/swr/pull/2576, | ||
// we need to update these fields in the `memorizedSnapshot` too | ||
// with direct mutations to ensure the snapshot is always up-to-date | ||
// even for the unselected fields, but only trigger re-renders when | ||
// the selected fields are changed. | ||
memorizedSnapshot.data = newSnapshot.data; | ||
memorizedSnapshot.isLoading = newSnapshot.isLoading; | ||
memorizedSnapshot.isValidating = newSnapshot.isValidating; | ||
memorizedSnapshot.error = newSnapshot.error; | ||
return memorizedSnapshot; | ||
} else { | ||
memorizedSnapshot = newSnapshot; | ||
return newSnapshot; | ||
} | ||
}, | ||
()=>serverSnapshot | ||
]; | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, [ | ||
cache, | ||
key | ||
]); | ||
// Get the current state that SWR should return. | ||
const cached = index_js.useSyncExternalStore(React.useCallback((callback)=>subscribeCache(key, (current, prev)=>{ | ||
if (!isEqual(prev, current)) callback(); | ||
}), // eslint-disable-next-line react-hooks/exhaustive-deps | ||
[ | ||
cache, | ||
key | ||
]), getSnapshot[0], getSnapshot[1]); | ||
const isInitialMount = !initialMountedRef.current; | ||
const hasRevalidator = EVENT_REVALIDATORS[key] && EVENT_REVALIDATORS[key].length > 0; | ||
const cachedData = cached.data; | ||
const data = _internal.isUndefined(cachedData) ? fallback : cachedData; | ||
const error = cached.error; | ||
// Use a ref to store previously returned data. Use the initial data as its initial value. | ||
const laggyDataRef = React.useRef(data); | ||
const returnedData = keepPreviousData ? _internal.isUndefined(cachedData) ? laggyDataRef.current : cachedData : data; | ||
// - 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. | ||
const shouldDoInitialRevalidation = (()=>{ | ||
// if a key already has revalidators and also has error, we should not trigger revalidation | ||
if (hasRevalidator && !_internal.isUndefined(error)) return false; | ||
// If `revalidateOnMount` is set, we take the value directly. | ||
if (isInitialMount && !_internal.isUndefined(revalidateOnMount)) return revalidateOnMount; | ||
// If it's paused, we skip revalidation. | ||
if (getConfig().isPaused()) return false; | ||
// Under suspense mode, it will always fetch on render if there is no | ||
// stale data so no need to revalidate immediately mount it again. | ||
// If data exists, only revalidate if `revalidateIfStale` is true. | ||
if (suspense) return _internal.isUndefined(data) ? false : revalidateIfStale; | ||
// If there is no stale data, we need to revalidate when mount; | ||
// If `revalidateIfStale` is set to true, we will always revalidate. | ||
return _internal.isUndefined(data) || revalidateIfStale; | ||
})(); | ||
// Resolve the default validating state: | ||
// If it's able to validate, and it should revalidate when mount, this will be true. | ||
const defaultValidatingState = !!(key && fetcher && isInitialMount && shouldDoInitialRevalidation); | ||
const isValidating = _internal.isUndefined(cached.isValidating) ? defaultValidatingState : cached.isValidating; | ||
const isLoading = _internal.isUndefined(cached.isLoading) ? defaultValidatingState : cached.isLoading; | ||
// The revalidation function is a carefully crafted wrapper of the original | ||
// `fetcher`, to correctly handle the many edge cases. | ||
const revalidate = React.useCallback(async (revalidateOpts)=>{ | ||
const currentFetcher = fetcherRef.current; | ||
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) { | ||
return false; | ||
} | ||
let newData; | ||
let startAt; | ||
let loading = true; | ||
const opts = revalidateOpts || {}; | ||
// If there is no ongoing concurrent request, or `dedupe` is not set, a | ||
// new request should be initiated. | ||
const shouldStartNewRequest = !FETCH[key] || !opts.dedupe; | ||
/* | ||
For React 17 | ||
Do unmount check for calls: | ||
If key has changed during the revalidation, or the component has been | ||
unmounted, old dispatch and old event callbacks should not take any | ||
effect | ||
For React 18 | ||
only check if key has changed | ||
https://github.com/reactwg/react-18/discussions/82 | ||
*/ const callbackSafeguard = ()=>{ | ||
if (_internal.IS_REACT_LEGACY) { | ||
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current; | ||
} | ||
return key === keyRef.current; | ||
}; | ||
// The final state object when the request finishes. | ||
const finalState = { | ||
isValidating: false, | ||
isLoading: false | ||
}; | ||
const finishRequestAndUpdateState = ()=>{ | ||
setCache(finalState); | ||
}; | ||
const cleanupState = ()=>{ | ||
// Check if it's still the same request before deleting it. | ||
const requestInfo = FETCH[key]; | ||
if (requestInfo && requestInfo[1] === startAt) { | ||
delete FETCH[key]; | ||
} | ||
}; | ||
// Start fetching. Change the `isValidating` state, update the cache. | ||
const initialState = { | ||
isValidating: true | ||
}; | ||
// It is in the `isLoading` state, if and only if there is no cached data. | ||
// This bypasses fallback data and laggy data. | ||
if (_internal.isUndefined(getCache().data)) { | ||
initialState.isLoading = true; | ||
} | ||
try { | ||
if (shouldStartNewRequest) { | ||
setCache(initialState); | ||
// If no cache is being rendered currently (it shows a blank page), | ||
// we trigger the loading slow event. | ||
if (config.loadingTimeout && _internal.isUndefined(getCache().data)) { | ||
setTimeout(()=>{ | ||
if (loading && callbackSafeguard()) { | ||
getConfig().onLoadingSlow(key, config); | ||
} | ||
}, config.loadingTimeout); | ||
} | ||
// Start the request and save the timestamp. | ||
// Key must be truthy if entering here. | ||
FETCH[key] = [ | ||
currentFetcher(fnArg), | ||
_internal.getTimestamp() | ||
]; | ||
} | ||
[newData, startAt] = FETCH[key]; | ||
newData = await newData; | ||
if (shouldStartNewRequest) { | ||
// If the request isn't interrupted, clean it up after the | ||
// deduplication interval. | ||
setTimeout(cleanupState, config.dedupingInterval); | ||
} | ||
// If there're other ongoing request(s), started after the current one, | ||
// we need to ignore the current one to avoid possible race conditions: | ||
// req1------------------>res1 (current one) | ||
// req2---------------->res2 | ||
// the request that fired later will always be kept. | ||
// The timestamp maybe be `undefined` or a number | ||
if (!FETCH[key] || FETCH[key][1] !== startAt) { | ||
if (shouldStartNewRequest) { | ||
if (callbackSafeguard()) { | ||
getConfig().onDiscarded(key); | ||
} | ||
} | ||
return false; | ||
} | ||
// Clear error. | ||
finalState.error = _internal.UNDEFINED; | ||
// If there're other mutations(s), that overlapped with the current revalidation: | ||
// case 1: | ||
// req------------------>res | ||
// mutate------>end | ||
// case 2: | ||
// req------------>res | ||
// mutate------>end | ||
// case 3: | ||
// req------------------>res | ||
// mutate-------...----------> | ||
// we have to ignore the revalidation result (res) because it's no longer fresh. | ||
// meanwhile, a new revalidation should be triggered when the mutation ends. | ||
const mutationInfo = MUTATION[key]; | ||
if (!_internal.isUndefined(mutationInfo) && // case 1 | ||
(startAt <= mutationInfo[0] || // case 2 | ||
startAt <= mutationInfo[1] || // case 3 | ||
mutationInfo[1] === 0)) { | ||
finishRequestAndUpdateState(); | ||
if (shouldStartNewRequest) { | ||
if (callbackSafeguard()) { | ||
getConfig().onDiscarded(key); | ||
} | ||
} | ||
return false; | ||
} | ||
// Deep compare with the latest state to avoid extra re-renders. | ||
// For local state, compare and assign. | ||
const cacheData = getCache().data; | ||
// Since the compare fn could be custom fn | ||
// cacheData might be different from newData even when compare fn returns True | ||
finalState.data = compare(cacheData, newData) ? cacheData : newData; | ||
// Trigger the successful callback if it's the original request. | ||
if (shouldStartNewRequest) { | ||
if (callbackSafeguard()) { | ||
getConfig().onSuccess(newData, key, config); | ||
} | ||
} | ||
} catch (err) { | ||
cleanupState(); | ||
const currentConfig = getConfig(); | ||
const { shouldRetryOnError } = currentConfig; | ||
// Not paused, we continue handling the error. Otherwise, discard it. | ||
if (!currentConfig.isPaused()) { | ||
// Get a new error, don't use deep comparison for errors. | ||
finalState.error = err; | ||
// Error event and retry logic. Only for the actual request, not | ||
// deduped ones. | ||
if (shouldStartNewRequest && callbackSafeguard()) { | ||
currentConfig.onError(err, key, currentConfig); | ||
if (shouldRetryOnError === true || _internal.isFunction(shouldRetryOnError) && shouldRetryOnError(err)) { | ||
if (!getConfig().revalidateOnFocus || !getConfig().revalidateOnReconnect || isActive()) { | ||
// If it's inactive, stop. It will auto-revalidate when | ||
// refocusing or reconnecting. | ||
// When retrying, deduplication is always enabled. | ||
currentConfig.onErrorRetry(err, key, currentConfig, (_opts)=>{ | ||
const revalidators = EVENT_REVALIDATORS[key]; | ||
if (revalidators && revalidators[0]) { | ||
revalidators[0](_internal.revalidateEvents.ERROR_REVALIDATE_EVENT, _opts); | ||
} | ||
}, { | ||
retryCount: (opts.retryCount || 0) + 1, | ||
dedupe: true | ||
}); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
// Mark loading as stopped. | ||
loading = false; | ||
// Update the current hook's state. | ||
finishRequestAndUpdateState(); | ||
return true; | ||
}, // `setState` is immutable, and `eventsCallback`, `fnArg`, and | ||
// `keyValidating` are depending on `key`, so we can exclude them from | ||
// the deps array. | ||
// | ||
// FIXME: | ||
// `fn` and `config` might be changed during the lifecycle, | ||
// but they might be changed every render like this. | ||
// `useSWR('key', () => fetch('/api/'), { suspense: true })` | ||
// So we omit the values from the deps array | ||
// even though it might cause unexpected behaviors. | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
[ | ||
key, | ||
cache | ||
]); | ||
// Similar to the global mutate but bound to the current cache and key. | ||
// `cache` isn't allowed to change during the lifecycle. | ||
const boundMutate = React.useCallback(// Use callback to make sure `keyRef.current` returns latest result every time | ||
(...args)=>{ | ||
return _internal.internalMutate(cache, keyRef.current, ...args); | ||
}, // eslint-disable-next-line react-hooks/exhaustive-deps | ||
[]); | ||
// The logic for updating refs. | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
fetcherRef.current = fetcher; | ||
configRef.current = config; | ||
// Handle laggy data updates. If there's cached data of the current key, | ||
// it'll be the correct reference. | ||
if (!_internal.isUndefined(cachedData)) { | ||
laggyDataRef.current = cachedData; | ||
} | ||
}); | ||
// After mounted or key changed. | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
if (!key) return; | ||
const softRevalidate = revalidate.bind(_internal.UNDEFINED, WITH_DEDUPE); | ||
// Expose revalidators to global event listeners. So we can trigger | ||
// revalidation from the outside. | ||
let nextFocusRevalidatedAt = 0; | ||
const onRevalidate = (type, opts = {})=>{ | ||
if (type == _internal.revalidateEvents.FOCUS_EVENT) { | ||
const now = Date.now(); | ||
if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) { | ||
nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval; | ||
softRevalidate(); | ||
} | ||
} else if (type == _internal.revalidateEvents.RECONNECT_EVENT) { | ||
if (getConfig().revalidateOnReconnect && isActive()) { | ||
softRevalidate(); | ||
} | ||
} else if (type == _internal.revalidateEvents.MUTATE_EVENT) { | ||
return revalidate(); | ||
} else if (type == _internal.revalidateEvents.ERROR_REVALIDATE_EVENT) { | ||
return revalidate(opts); | ||
} | ||
return; | ||
}; | ||
const unsubEvents = _internal.subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate); | ||
// Mark the component as mounted and update corresponding refs. | ||
unmountedRef.current = false; | ||
keyRef.current = key; | ||
initialMountedRef.current = true; | ||
// Keep the original key in the cache. | ||
setCache({ | ||
_k: fnArg | ||
}); | ||
// Trigger a revalidation | ||
if (shouldDoInitialRevalidation) { | ||
if (_internal.isUndefined(data) || _internal.IS_SERVER) { | ||
// Revalidate immediately. | ||
softRevalidate(); | ||
} else { | ||
// Delay the revalidate if we have data to return so we won't block | ||
// rendering. | ||
_internal.rAF(softRevalidate); | ||
} | ||
} | ||
return ()=>{ | ||
// Mark it as unmounted. | ||
unmountedRef.current = true; | ||
unsubEvents(); | ||
}; | ||
}, [ | ||
key | ||
]); | ||
// Polling | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
let timer; | ||
function next() { | ||
// Use the passed interval | ||
// ...or invoke the function with the updated data to get the interval | ||
const interval = _internal.isFunction(refreshInterval) ? refreshInterval(getCache().data) : refreshInterval; | ||
// We only start the next interval if `refreshInterval` is not 0, and: | ||
// - `force` is true, which is the start of polling | ||
// - or `timer` is not 0, which means the effect wasn't canceled | ||
if (interval && timer !== -1) { | ||
timer = setTimeout(execute, interval); | ||
} | ||
} | ||
function execute() { | ||
// Check if it's OK to execute: | ||
// Only revalidate when the page is visible, online, and not errored. | ||
if (!getCache().error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) { | ||
revalidate(WITH_DEDUPE).then(next); | ||
} else { | ||
// Schedule the next interval to check again. | ||
next(); | ||
} | ||
} | ||
next(); | ||
return ()=>{ | ||
if (timer) { | ||
clearTimeout(timer); | ||
timer = -1; | ||
} | ||
}; | ||
}, [ | ||
refreshInterval, | ||
refreshWhenHidden, | ||
refreshWhenOffline, | ||
key | ||
]); | ||
// Display debug info in React DevTools. | ||
React.useDebugValue(returnedData); | ||
// In Suspense mode, we can't return the empty `data` state. | ||
// If there is an `error`, the `error` needs to be thrown to the error boundary. | ||
// If there is no `error`, the `revalidation` promise needs to be thrown to | ||
// the suspense boundary. | ||
if (suspense && _internal.isUndefined(data) && key) { | ||
// SWR should throw when trying to use Suspense on the server with React 18, | ||
// without providing any fallback data. This causes hydration errors. See: | ||
// https://github.com/vercel/swr/issues/1832 | ||
if (!_internal.IS_REACT_LEGACY && _internal.IS_SERVER) { | ||
throw new Error('Fallback data is required when using Suspense in SSR.'); | ||
} | ||
// Always update fetcher and config refs even with the Suspense mode. | ||
fetcherRef.current = fetcher; | ||
configRef.current = config; | ||
unmountedRef.current = false; | ||
const req = PRELOAD[key]; | ||
if (!_internal.isUndefined(req)) { | ||
const promise = boundMutate(req); | ||
use(promise); | ||
} | ||
if (_internal.isUndefined(error)) { | ||
const promise = revalidate(WITH_DEDUPE); | ||
if (!_internal.isUndefined(returnedData)) { | ||
promise.status = 'fulfilled'; | ||
promise.value = true; | ||
} | ||
use(promise); | ||
} else { | ||
throw error; | ||
} | ||
} | ||
return { | ||
mutate: boundMutate, | ||
get data () { | ||
stateDependencies.data = true; | ||
return returnedData; | ||
}, | ||
get error () { | ||
stateDependencies.error = true; | ||
return error; | ||
}, | ||
get isValidating () { | ||
stateDependencies.isValidating = true; | ||
return isValidating; | ||
}, | ||
get isLoading () { | ||
stateDependencies.isLoading = true; | ||
return isLoading; | ||
} | ||
}; | ||
}; | ||
_internal.OBJECT.defineProperty(_internal.SWRConfig, 'defaultValue', { | ||
value: _internal.defaultConfig | ||
}); | ||
/** | ||
* A hook to fetch data. | ||
* | ||
* @link https://swr.vercel.app | ||
* @example | ||
* ```jsx | ||
* import useSWR from 'swr' | ||
* function Profile() { | ||
* const { data, error, isLoading } = useSWR('/api/user', fetcher) | ||
* if (error) return <div>failed to load</div> | ||
* if (isLoading) return <div>loading...</div> | ||
* return <div>hello {data.name}!</div> | ||
* } | ||
* ``` | ||
*/ const useSWR = _internal.withArgs(useSWRHandler); | ||
const immutable = (useSWRNext)=>(key, fetcher, config)=>{ | ||
@@ -560,5 +17,5 @@ // Always override all revalidate options. | ||
}; | ||
const useSWRImmutable = _internal.withMiddleware(useSWR, immutable); | ||
const useSWRImmutable = index_js.withMiddleware(useSWR__default.default, immutable); | ||
exports.default = useSWRImmutable; | ||
exports.immutable = immutable; |
Object.defineProperty(exports, '__esModule', { value: true }); | ||
var React = require('react'); | ||
var index_js = require('use-sync-external-store/shim/index.js'); | ||
var _internal = require('swr/_internal'); | ||
var react = require('react'); | ||
var useSWR = require('../index/index.js'); | ||
var index_js = require('../_internal/index.js'); | ||
var index_js$1 = require('use-sync-external-store/shim/index.js'); | ||
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } | ||
var React__default = /*#__PURE__*/_interopDefault(React); | ||
var useSWR__default = /*#__PURE__*/_interopDefault(useSWR); | ||
/// <reference types="react/experimental" /> | ||
const use = React__default.default.use || // This extra generic is to avoid TypeScript mixing up the generic and JSX sytax | ||
// and emitting an error. | ||
// We assume that this is only for the `use(thenable)` case, not `use(context)`. | ||
// https://github.com/facebook/react/blob/aed00dacfb79d17c53218404c52b1c7aa59c4a89/packages/react-server/src/ReactFizzThenable.js#L45 | ||
((thenable)=>{ | ||
switch(thenable.status){ | ||
case 'pending': | ||
throw thenable; | ||
case 'fulfilled': | ||
return thenable.value; | ||
case 'rejected': | ||
throw thenable.reason; | ||
default: | ||
thenable.status = 'pending'; | ||
thenable.then((v)=>{ | ||
thenable.status = 'fulfilled'; | ||
thenable.value = v; | ||
}, (e)=>{ | ||
thenable.status = 'rejected'; | ||
thenable.reason = e; | ||
}); | ||
throw thenable; | ||
} | ||
}); | ||
const WITH_DEDUPE = { | ||
dedupe: true | ||
}; | ||
const useSWRHandler = (_key, fetcher, config)=>{ | ||
const { cache, compare, suspense, fallbackData, revalidateOnMount, revalidateIfStale, refreshInterval, refreshWhenHidden, refreshWhenOffline, keepPreviousData } = config; | ||
const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = _internal.SWRGlobalState.get(cache); | ||
// `key` is the identifier of the SWR internal state, | ||
// `fnArg` is the argument/arguments parsed from the key, which will be passed | ||
// to the fetcher. | ||
// All of them are derived from `_key`. | ||
const [key, fnArg] = _internal.serialize(_key); | ||
// If it's the initial render of this hook. | ||
const initialMountedRef = React.useRef(false); | ||
// If the hook is unmounted already. This will be used to prevent some effects | ||
// to be called after unmounting. | ||
const unmountedRef = React.useRef(false); | ||
// Refs to keep the key and config. | ||
const keyRef = React.useRef(key); | ||
const fetcherRef = React.useRef(fetcher); | ||
const configRef = React.useRef(config); | ||
const getConfig = ()=>configRef.current; | ||
const isActive = ()=>getConfig().isVisible() && getConfig().isOnline(); | ||
const [getCache, setCache, subscribeCache, getInitialCache] = _internal.createCacheHelper(cache, key); | ||
const stateDependencies = React.useRef({}).current; | ||
// Resolve the fallback data from either the inline option, or the global provider. | ||
// If it's a promise, we simply let React suspend and resolve it for us. | ||
let fallback = _internal.isUndefined(fallbackData) ? _internal.isUndefined(config.fallback) ? _internal.UNDEFINED : config.fallback[key] : fallbackData; | ||
if (fallback && _internal.isPromiseLike(fallback)) { | ||
fallback = use(fallback); | ||
} | ||
const isEqual = (prev, current)=>{ | ||
for(const _ in stateDependencies){ | ||
const t = _; | ||
if (t === 'data') { | ||
if (!compare(prev[t], current[t])) { | ||
if (!_internal.isUndefined(prev[t])) { | ||
return false; | ||
} | ||
if (!compare(returnedData, current[t])) { | ||
return false; | ||
} | ||
} | ||
} else { | ||
if (current[t] !== prev[t]) { | ||
return false; | ||
} | ||
// Shared state between server components and client components | ||
const noop = ()=>{}; | ||
// Using noop() as the undefined value as undefined can be replaced | ||
// by something else. Prettier ignore and extra parentheses are necessary here | ||
// to ensure that tsc doesn't remove the __NOINLINE__ comment. | ||
// prettier-ignore | ||
const UNDEFINED = /*#__NOINLINE__*/ noop(); | ||
const OBJECT = Object; | ||
const isUndefined = (v)=>v === UNDEFINED; | ||
const isFunction = (v)=>typeof v == 'function'; | ||
// use WeakMap to store the object->key mapping | ||
// so the objects can be garbage collected. | ||
// WeakMap uses a hashtable under the hood, so the lookup | ||
// complexity is almost O(1). | ||
const table = new WeakMap(); | ||
const isObjectType = (value, type)=>OBJECT.prototype.toString.call(value) === `[object ${type}]`; | ||
// counter of the key | ||
let counter = 0; | ||
// A stable hash implementation that supports: | ||
// - Fast and ensures unique hash properties | ||
// - Handles unserializable values | ||
// - Handles object key ordering | ||
// - Generates short results | ||
// | ||
// This is not a serialization function, and the result is not guaranteed to be | ||
// parsable. | ||
const stableHash = (arg)=>{ | ||
const type = typeof arg; | ||
const isDate = isObjectType(arg, 'Date'); | ||
const isRegex = isObjectType(arg, 'RegExp'); | ||
const isPlainObject = isObjectType(arg, 'Object'); | ||
let result; | ||
let index; | ||
if (OBJECT(arg) === arg && !isDate && !isRegex) { | ||
// Object/function, not null/date/regexp. Use WeakMap to store the id first. | ||
// If it's already hashed, directly return the result. | ||
result = table.get(arg); | ||
if (result) return result; | ||
// Store the hash first for circular reference detection before entering the | ||
// recursive `stableHash` calls. | ||
// For other objects like set and map, we use this id directly as the hash. | ||
result = ++counter + '~'; | ||
table.set(arg, result); | ||
if (Array.isArray(arg)) { | ||
// Array. | ||
result = '@'; | ||
for(index = 0; index < arg.length; index++){ | ||
result += stableHash(arg[index]) + ','; | ||
} | ||
table.set(arg, result); | ||
} | ||
return true; | ||
}; | ||
const getSnapshot = React.useMemo(()=>{ | ||
const shouldStartRequest = (()=>{ | ||
if (!key) return false; | ||
if (!fetcher) return false; | ||
// If `revalidateOnMount` is set, we take the value directly. | ||
if (!_internal.isUndefined(revalidateOnMount)) return revalidateOnMount; | ||
// If it's paused, we skip revalidation. | ||
if (getConfig().isPaused()) return false; | ||
if (suspense) return false; | ||
return revalidateIfStale !== false; | ||
})(); | ||
// Get the cache and merge it with expected states. | ||
const getSelectedCache = (state)=>{ | ||
// We only select the needed fields from the state. | ||
const snapshot = _internal.mergeObjects(state); | ||
delete snapshot._k; | ||
if (!shouldStartRequest) { | ||
return snapshot; | ||
if (isPlainObject) { | ||
// Object, sort keys. | ||
result = '#'; | ||
const keys = OBJECT.keys(arg).sort(); | ||
while(!isUndefined(index = keys.pop())){ | ||
if (!isUndefined(arg[index])) { | ||
result += index + ':' + stableHash(arg[index]) + ','; | ||
} | ||
} | ||
return { | ||
isValidating: true, | ||
isLoading: true, | ||
...snapshot | ||
}; | ||
}; | ||
const cachedData = getCache(); | ||
const initialData = getInitialCache(); | ||
const clientSnapshot = getSelectedCache(cachedData); | ||
const serverSnapshot = cachedData === initialData ? clientSnapshot : getSelectedCache(initialData); | ||
// To make sure that we are returning the same object reference to avoid | ||
// unnecessary re-renders, we keep the previous snapshot and use deep | ||
// comparison to check if we need to return a new one. | ||
let memorizedSnapshot = clientSnapshot; | ||
return [ | ||
()=>{ | ||
const newSnapshot = getSelectedCache(getCache()); | ||
const compareResult = isEqual(newSnapshot, memorizedSnapshot); | ||
if (compareResult) { | ||
// Mentally, we should always return the `memorizedSnapshot` here | ||
// as there's no change between the new and old snapshots. | ||
// However, since the `isEqual` function only compares selected fields, | ||
// the values of the unselected fields might be changed. That's | ||
// simply because we didn't track them. | ||
// To support the case in https://github.com/vercel/swr/pull/2576, | ||
// we need to update these fields in the `memorizedSnapshot` too | ||
// with direct mutations to ensure the snapshot is always up-to-date | ||
// even for the unselected fields, but only trigger re-renders when | ||
// the selected fields are changed. | ||
memorizedSnapshot.data = newSnapshot.data; | ||
memorizedSnapshot.isLoading = newSnapshot.isLoading; | ||
memorizedSnapshot.isValidating = newSnapshot.isValidating; | ||
memorizedSnapshot.error = newSnapshot.error; | ||
return memorizedSnapshot; | ||
} else { | ||
memorizedSnapshot = newSnapshot; | ||
return newSnapshot; | ||
} | ||
}, | ||
()=>serverSnapshot | ||
]; | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, [ | ||
cache, | ||
key | ||
]); | ||
// Get the current state that SWR should return. | ||
const cached = index_js.useSyncExternalStore(React.useCallback((callback)=>subscribeCache(key, (current, prev)=>{ | ||
if (!isEqual(prev, current)) callback(); | ||
}), // eslint-disable-next-line react-hooks/exhaustive-deps | ||
[ | ||
cache, | ||
key | ||
]), getSnapshot[0], getSnapshot[1]); | ||
const isInitialMount = !initialMountedRef.current; | ||
const hasRevalidator = EVENT_REVALIDATORS[key] && EVENT_REVALIDATORS[key].length > 0; | ||
const cachedData = cached.data; | ||
const data = _internal.isUndefined(cachedData) ? fallback : cachedData; | ||
const error = cached.error; | ||
// Use a ref to store previously returned data. Use the initial data as its initial value. | ||
const laggyDataRef = React.useRef(data); | ||
const returnedData = keepPreviousData ? _internal.isUndefined(cachedData) ? laggyDataRef.current : cachedData : data; | ||
// - 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. | ||
const shouldDoInitialRevalidation = (()=>{ | ||
// if a key already has revalidators and also has error, we should not trigger revalidation | ||
if (hasRevalidator && !_internal.isUndefined(error)) return false; | ||
// If `revalidateOnMount` is set, we take the value directly. | ||
if (isInitialMount && !_internal.isUndefined(revalidateOnMount)) return revalidateOnMount; | ||
// If it's paused, we skip revalidation. | ||
if (getConfig().isPaused()) return false; | ||
// Under suspense mode, it will always fetch on render if there is no | ||
// stale data so no need to revalidate immediately mount it again. | ||
// If data exists, only revalidate if `revalidateIfStale` is true. | ||
if (suspense) return _internal.isUndefined(data) ? false : revalidateIfStale; | ||
// If there is no stale data, we need to revalidate when mount; | ||
// If `revalidateIfStale` is set to true, we will always revalidate. | ||
return _internal.isUndefined(data) || revalidateIfStale; | ||
})(); | ||
// Resolve the default validating state: | ||
// If it's able to validate, and it should revalidate when mount, this will be true. | ||
const defaultValidatingState = !!(key && fetcher && isInitialMount && shouldDoInitialRevalidation); | ||
const isValidating = _internal.isUndefined(cached.isValidating) ? defaultValidatingState : cached.isValidating; | ||
const isLoading = _internal.isUndefined(cached.isLoading) ? defaultValidatingState : cached.isLoading; | ||
// The revalidation function is a carefully crafted wrapper of the original | ||
// `fetcher`, to correctly handle the many edge cases. | ||
const revalidate = React.useCallback(async (revalidateOpts)=>{ | ||
const currentFetcher = fetcherRef.current; | ||
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) { | ||
return false; | ||
table.set(arg, result); | ||
} | ||
let newData; | ||
let startAt; | ||
let loading = true; | ||
const opts = revalidateOpts || {}; | ||
// If there is no ongoing concurrent request, or `dedupe` is not set, a | ||
// new request should be initiated. | ||
const shouldStartNewRequest = !FETCH[key] || !opts.dedupe; | ||
/* | ||
For React 17 | ||
Do unmount check for calls: | ||
If key has changed during the revalidation, or the component has been | ||
unmounted, old dispatch and old event callbacks should not take any | ||
effect | ||
} else { | ||
result = isDate ? arg.toJSON() : type == 'symbol' ? arg.toString() : type == 'string' ? JSON.stringify(arg) : '' + arg; | ||
} | ||
return result; | ||
}; | ||
For React 18 | ||
only check if key has changed | ||
https://github.com/reactwg/react-18/discussions/82 | ||
*/ const callbackSafeguard = ()=>{ | ||
if (_internal.IS_REACT_LEGACY) { | ||
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current; | ||
} | ||
return key === keyRef.current; | ||
}; | ||
// The final state object when the request finishes. | ||
const finalState = { | ||
isValidating: false, | ||
isLoading: false | ||
}; | ||
const finishRequestAndUpdateState = ()=>{ | ||
setCache(finalState); | ||
}; | ||
const cleanupState = ()=>{ | ||
// Check if it's still the same request before deleting it. | ||
const requestInfo = FETCH[key]; | ||
if (requestInfo && requestInfo[1] === startAt) { | ||
delete FETCH[key]; | ||
} | ||
}; | ||
// Start fetching. Change the `isValidating` state, update the cache. | ||
const initialState = { | ||
isValidating: true | ||
}; | ||
// It is in the `isLoading` state, if and only if there is no cached data. | ||
// This bypasses fallback data and laggy data. | ||
if (_internal.isUndefined(getCache().data)) { | ||
initialState.isLoading = true; | ||
} | ||
const serialize = (key)=>{ | ||
if (isFunction(key)) { | ||
try { | ||
if (shouldStartNewRequest) { | ||
setCache(initialState); | ||
// If no cache is being rendered currently (it shows a blank page), | ||
// we trigger the loading slow event. | ||
if (config.loadingTimeout && _internal.isUndefined(getCache().data)) { | ||
setTimeout(()=>{ | ||
if (loading && callbackSafeguard()) { | ||
getConfig().onLoadingSlow(key, config); | ||
} | ||
}, config.loadingTimeout); | ||
} | ||
// Start the request and save the timestamp. | ||
// Key must be truthy if entering here. | ||
FETCH[key] = [ | ||
currentFetcher(fnArg), | ||
_internal.getTimestamp() | ||
]; | ||
} | ||
[newData, startAt] = FETCH[key]; | ||
newData = await newData; | ||
if (shouldStartNewRequest) { | ||
// If the request isn't interrupted, clean it up after the | ||
// deduplication interval. | ||
setTimeout(cleanupState, config.dedupingInterval); | ||
} | ||
// If there're other ongoing request(s), started after the current one, | ||
// we need to ignore the current one to avoid possible race conditions: | ||
// req1------------------>res1 (current one) | ||
// req2---------------->res2 | ||
// the request that fired later will always be kept. | ||
// The timestamp maybe be `undefined` or a number | ||
if (!FETCH[key] || FETCH[key][1] !== startAt) { | ||
if (shouldStartNewRequest) { | ||
if (callbackSafeguard()) { | ||
getConfig().onDiscarded(key); | ||
} | ||
} | ||
return false; | ||
} | ||
// Clear error. | ||
finalState.error = _internal.UNDEFINED; | ||
// If there're other mutations(s), that overlapped with the current revalidation: | ||
// case 1: | ||
// req------------------>res | ||
// mutate------>end | ||
// case 2: | ||
// req------------>res | ||
// mutate------>end | ||
// case 3: | ||
// req------------------>res | ||
// mutate-------...----------> | ||
// we have to ignore the revalidation result (res) because it's no longer fresh. | ||
// meanwhile, a new revalidation should be triggered when the mutation ends. | ||
const mutationInfo = MUTATION[key]; | ||
if (!_internal.isUndefined(mutationInfo) && // case 1 | ||
(startAt <= mutationInfo[0] || // case 2 | ||
startAt <= mutationInfo[1] || // case 3 | ||
mutationInfo[1] === 0)) { | ||
finishRequestAndUpdateState(); | ||
if (shouldStartNewRequest) { | ||
if (callbackSafeguard()) { | ||
getConfig().onDiscarded(key); | ||
} | ||
} | ||
return false; | ||
} | ||
// Deep compare with the latest state to avoid extra re-renders. | ||
// For local state, compare and assign. | ||
const cacheData = getCache().data; | ||
// Since the compare fn could be custom fn | ||
// cacheData might be different from newData even when compare fn returns True | ||
finalState.data = compare(cacheData, newData) ? cacheData : newData; | ||
// Trigger the successful callback if it's the original request. | ||
if (shouldStartNewRequest) { | ||
if (callbackSafeguard()) { | ||
getConfig().onSuccess(newData, key, config); | ||
} | ||
} | ||
key = key(); | ||
} catch (err) { | ||
cleanupState(); | ||
const currentConfig = getConfig(); | ||
const { shouldRetryOnError } = currentConfig; | ||
// Not paused, we continue handling the error. Otherwise, discard it. | ||
if (!currentConfig.isPaused()) { | ||
// Get a new error, don't use deep comparison for errors. | ||
finalState.error = err; | ||
// Error event and retry logic. Only for the actual request, not | ||
// deduped ones. | ||
if (shouldStartNewRequest && callbackSafeguard()) { | ||
currentConfig.onError(err, key, currentConfig); | ||
if (shouldRetryOnError === true || _internal.isFunction(shouldRetryOnError) && shouldRetryOnError(err)) { | ||
if (!getConfig().revalidateOnFocus || !getConfig().revalidateOnReconnect || isActive()) { | ||
// If it's inactive, stop. It will auto-revalidate when | ||
// refocusing or reconnecting. | ||
// When retrying, deduplication is always enabled. | ||
currentConfig.onErrorRetry(err, key, currentConfig, (_opts)=>{ | ||
const revalidators = EVENT_REVALIDATORS[key]; | ||
if (revalidators && revalidators[0]) { | ||
revalidators[0](_internal.revalidateEvents.ERROR_REVALIDATE_EVENT, _opts); | ||
} | ||
}, { | ||
retryCount: (opts.retryCount || 0) + 1, | ||
dedupe: true | ||
}); | ||
} | ||
} | ||
} | ||
} | ||
// dependencies not ready | ||
key = ''; | ||
} | ||
// Mark loading as stopped. | ||
loading = false; | ||
// Update the current hook's state. | ||
finishRequestAndUpdateState(); | ||
return true; | ||
}, // `setState` is immutable, and `eventsCallback`, `fnArg`, and | ||
// `keyValidating` are depending on `key`, so we can exclude them from | ||
// the deps array. | ||
// | ||
// FIXME: | ||
// `fn` and `config` might be changed during the lifecycle, | ||
// but they might be changed every render like this. | ||
// `useSWR('key', () => fetch('/api/'), { suspense: true })` | ||
// So we omit the values from the deps array | ||
// even though it might cause unexpected behaviors. | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
[ | ||
} | ||
// Use the original key as the argument of fetcher. This can be a string or an | ||
// array of values. | ||
const args = key; | ||
// If key is not falsy, or not an empty array, hash it. | ||
key = typeof key == 'string' ? key : (Array.isArray(key) ? key.length : key) ? stableHash(key) : ''; | ||
return [ | ||
key, | ||
cache | ||
]); | ||
// Similar to the global mutate but bound to the current cache and key. | ||
// `cache` isn't allowed to change during the lifecycle. | ||
const boundMutate = React.useCallback(// Use callback to make sure `keyRef.current` returns latest result every time | ||
(...args)=>{ | ||
return _internal.internalMutate(cache, keyRef.current, ...args); | ||
}, // eslint-disable-next-line react-hooks/exhaustive-deps | ||
[]); | ||
// The logic for updating refs. | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
fetcherRef.current = fetcher; | ||
configRef.current = config; | ||
// Handle laggy data updates. If there's cached data of the current key, | ||
// it'll be the correct reference. | ||
if (!_internal.isUndefined(cachedData)) { | ||
laggyDataRef.current = cachedData; | ||
} | ||
}); | ||
// After mounted or key changed. | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
if (!key) return; | ||
const softRevalidate = revalidate.bind(_internal.UNDEFINED, WITH_DEDUPE); | ||
// Expose revalidators to global event listeners. So we can trigger | ||
// revalidation from the outside. | ||
let nextFocusRevalidatedAt = 0; | ||
const onRevalidate = (type, opts = {})=>{ | ||
if (type == _internal.revalidateEvents.FOCUS_EVENT) { | ||
const now = Date.now(); | ||
if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) { | ||
nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval; | ||
softRevalidate(); | ||
} | ||
} else if (type == _internal.revalidateEvents.RECONNECT_EVENT) { | ||
if (getConfig().revalidateOnReconnect && isActive()) { | ||
softRevalidate(); | ||
} | ||
} else if (type == _internal.revalidateEvents.MUTATE_EVENT) { | ||
return revalidate(); | ||
} else if (type == _internal.revalidateEvents.ERROR_REVALIDATE_EVENT) { | ||
return revalidate(opts); | ||
} | ||
return; | ||
}; | ||
const unsubEvents = _internal.subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate); | ||
// Mark the component as mounted and update corresponding refs. | ||
unmountedRef.current = false; | ||
keyRef.current = key; | ||
initialMountedRef.current = true; | ||
// Keep the original key in the cache. | ||
setCache({ | ||
_k: fnArg | ||
}); | ||
// Trigger a revalidation | ||
if (shouldDoInitialRevalidation) { | ||
if (_internal.isUndefined(data) || _internal.IS_SERVER) { | ||
// Revalidate immediately. | ||
softRevalidate(); | ||
} else { | ||
// Delay the revalidate if we have data to return so we won't block | ||
// rendering. | ||
_internal.rAF(softRevalidate); | ||
} | ||
} | ||
return ()=>{ | ||
// Mark it as unmounted. | ||
unmountedRef.current = true; | ||
unsubEvents(); | ||
}; | ||
}, [ | ||
key | ||
]); | ||
// Polling | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
let timer; | ||
function next() { | ||
// Use the passed interval | ||
// ...or invoke the function with the updated data to get the interval | ||
const interval = _internal.isFunction(refreshInterval) ? refreshInterval(getCache().data) : refreshInterval; | ||
// We only start the next interval if `refreshInterval` is not 0, and: | ||
// - `force` is true, which is the start of polling | ||
// - or `timer` is not 0, which means the effect wasn't canceled | ||
if (interval && timer !== -1) { | ||
timer = setTimeout(execute, interval); | ||
} | ||
} | ||
function execute() { | ||
// Check if it's OK to execute: | ||
// Only revalidate when the page is visible, online, and not errored. | ||
if (!getCache().error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) { | ||
revalidate(WITH_DEDUPE).then(next); | ||
} else { | ||
// Schedule the next interval to check again. | ||
next(); | ||
} | ||
} | ||
next(); | ||
return ()=>{ | ||
if (timer) { | ||
clearTimeout(timer); | ||
timer = -1; | ||
} | ||
}; | ||
}, [ | ||
refreshInterval, | ||
refreshWhenHidden, | ||
refreshWhenOffline, | ||
key | ||
]); | ||
// Display debug info in React DevTools. | ||
React.useDebugValue(returnedData); | ||
// In Suspense mode, we can't return the empty `data` state. | ||
// If there is an `error`, the `error` needs to be thrown to the error boundary. | ||
// If there is no `error`, the `revalidation` promise needs to be thrown to | ||
// the suspense boundary. | ||
if (suspense && _internal.isUndefined(data) && key) { | ||
// SWR should throw when trying to use Suspense on the server with React 18, | ||
// without providing any fallback data. This causes hydration errors. See: | ||
// https://github.com/vercel/swr/issues/1832 | ||
if (!_internal.IS_REACT_LEGACY && _internal.IS_SERVER) { | ||
throw new Error('Fallback data is required when using Suspense in SSR.'); | ||
} | ||
// Always update fetcher and config refs even with the Suspense mode. | ||
fetcherRef.current = fetcher; | ||
configRef.current = config; | ||
unmountedRef.current = false; | ||
const req = PRELOAD[key]; | ||
if (!_internal.isUndefined(req)) { | ||
const promise = boundMutate(req); | ||
use(promise); | ||
} | ||
if (_internal.isUndefined(error)) { | ||
const promise = revalidate(WITH_DEDUPE); | ||
if (!_internal.isUndefined(returnedData)) { | ||
promise.status = 'fulfilled'; | ||
promise.value = true; | ||
} | ||
use(promise); | ||
} else { | ||
throw error; | ||
} | ||
} | ||
return { | ||
mutate: boundMutate, | ||
get data () { | ||
stateDependencies.data = true; | ||
return returnedData; | ||
}, | ||
get error () { | ||
stateDependencies.error = true; | ||
return error; | ||
}, | ||
get isValidating () { | ||
stateDependencies.isValidating = true; | ||
return isValidating; | ||
}, | ||
get isLoading () { | ||
stateDependencies.isLoading = true; | ||
return isLoading; | ||
} | ||
}; | ||
args | ||
]; | ||
}; | ||
_internal.OBJECT.defineProperty(_internal.SWRConfig, 'defaultValue', { | ||
value: _internal.defaultConfig | ||
}); | ||
/** | ||
* A hook to fetch data. | ||
* | ||
* @link https://swr.vercel.app | ||
* @example | ||
* ```jsx | ||
* import useSWR from 'swr' | ||
* function Profile() { | ||
* const { data, error, isLoading } = useSWR('/api/user', fetcher) | ||
* if (error) return <div>failed to load</div> | ||
* if (isLoading) return <div>loading...</div> | ||
* return <div>hello {data.name}!</div> | ||
* } | ||
* ``` | ||
*/ const useSWR = _internal.withArgs(useSWRHandler); | ||
const INFINITE_PREFIX = '$inf$'; | ||
const getFirstPageKey = (getKey)=>{ | ||
return _internal.serialize(getKey ? getKey(0, null) : null)[0]; | ||
return serialize(getKey ? getKey(0, null) : null)[0]; | ||
}; | ||
const unstable_serialize = (getKey)=>{ | ||
return _internal.INFINITE_PREFIX + getFirstPageKey(getKey); | ||
return INFINITE_PREFIX + getFirstPageKey(getKey); | ||
}; | ||
@@ -562,11 +112,7 @@ | ||
// hook where `key` and return type are not like the normal `useSWR` types. | ||
// const INFINITE_PREFIX = '$inf$' | ||
const EMPTY_PROMISE = Promise.resolve(); | ||
// export const unstable_serialize = (getKey: SWRInfiniteKeyLoader) => { | ||
// return INFINITE_PREFIX + getFirstPageKey(getKey) | ||
// } | ||
const infinite = (useSWRNext)=>(getKey, fn, config)=>{ | ||
const didMountRef = React.useRef(false); | ||
const didMountRef = react.useRef(false); | ||
const { cache, initialSize = 1, revalidateAll = false, persistSize = false, revalidateFirstPage = true, revalidateOnMount = false, parallel = false } = config; | ||
const [, , , PRELOAD] = _internal.SWRGlobalState.get(_internal.cache); | ||
const [, , , PRELOAD] = index_js.SWRGlobalState.get(index_js.cache); | ||
// The serialized key of the first page. This key will be used to store | ||
@@ -577,9 +123,9 @@ // metadata of this SWR infinite hook. | ||
infiniteKey = getFirstPageKey(getKey); | ||
if (infiniteKey) infiniteKey = _internal.INFINITE_PREFIX + infiniteKey; | ||
if (infiniteKey) infiniteKey = index_js.INFINITE_PREFIX + infiniteKey; | ||
} catch (err) { | ||
// Not ready yet. | ||
} | ||
const [get, set, subscribeCache] = _internal.createCacheHelper(cache, infiniteKey); | ||
const getSnapshot = React.useCallback(()=>{ | ||
const size = _internal.isUndefined(get()._l) ? initialSize : get()._l; | ||
const [get, set, subscribeCache] = index_js.createCacheHelper(cache, infiniteKey); | ||
const getSnapshot = react.useCallback(()=>{ | ||
const size = index_js.isUndefined(get()._l) ? initialSize : get()._l; | ||
return size; | ||
@@ -592,3 +138,3 @@ // eslint-disable-next-line react-hooks/exhaustive-deps | ||
]); | ||
index_js.useSyncExternalStore(React.useCallback((callback)=>{ | ||
index_js$1.useSyncExternalStore(react.useCallback((callback)=>{ | ||
if (infiniteKey) return subscribeCache(infiniteKey, ()=>{ | ||
@@ -603,5 +149,5 @@ callback(); | ||
]), getSnapshot, getSnapshot); | ||
const resolvePageSize = React.useCallback(()=>{ | ||
const resolvePageSize = react.useCallback(()=>{ | ||
const cachedPageSize = get()._l; | ||
return _internal.isUndefined(cachedPageSize) ? initialSize : cachedPageSize; | ||
return index_js.isUndefined(cachedPageSize) ? initialSize : cachedPageSize; | ||
// `cache` isn't allowed to change during the lifecycle | ||
@@ -614,5 +160,5 @@ // eslint-disable-next-line react-hooks/exhaustive-deps | ||
// keep the last page size to restore it with the persistSize option | ||
const lastPageSizeRef = React.useRef(resolvePageSize()); | ||
const lastPageSizeRef = react.useRef(resolvePageSize()); | ||
// When the page key changes, we reset the page size if it's not persisted | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
index_js.useIsomorphicLayoutEffect(()=>{ | ||
if (!didMountRef.current) { | ||
@@ -643,3 +189,3 @@ didMountRef.current = true; | ||
set({ | ||
_r: _internal.UNDEFINED | ||
_r: index_js.UNDEFINED | ||
}); | ||
@@ -649,3 +195,3 @@ // return an array of page data | ||
const pageSize = resolvePageSize(); | ||
const [getCache] = _internal.createCacheHelper(cache, key); | ||
const [getCache] = index_js.createCacheHelper(cache, key); | ||
const cacheData = getCache().data; | ||
@@ -655,7 +201,7 @@ const revalidators = []; | ||
for(let i = 0; i < pageSize; ++i){ | ||
const [pageKey, pageArg] = _internal.serialize(getKey(i, parallel ? null : previousPageData)); | ||
const [pageKey, pageArg] = index_js.serialize(getKey(i, parallel ? null : previousPageData)); | ||
if (!pageKey) { | ||
break; | ||
} | ||
const [getSWRCache, setSWRCache] = _internal.createCacheHelper(cache, pageKey); | ||
const [getSWRCache, setSWRCache] = index_js.createCacheHelper(cache, pageKey); | ||
// Get the cached page data. | ||
@@ -670,3 +216,3 @@ let pageData = getSWRCache().data; | ||
// - cache for that page has changed | ||
const shouldFetchPage = revalidateAll || forceRevalidateAll || _internal.isUndefined(pageData) || revalidateFirstPage && !i && !_internal.isUndefined(cacheData) || shouldRevalidateOnMount || cacheData && !_internal.isUndefined(cacheData[i]) && !config.compare(cacheData[i], pageData); | ||
const shouldFetchPage = revalidateAll || forceRevalidateAll || index_js.isUndefined(pageData) || revalidateFirstPage && !i && !index_js.isUndefined(cacheData) || shouldRevalidateOnMount || cacheData && !index_js.isUndefined(cacheData[i]) && !config.compare(cacheData[i], pageData); | ||
if (fn && (typeof shouldRevalidatePage === 'function' ? shouldRevalidatePage(pageData, pageArg) : shouldFetchPage)) { | ||
@@ -709,3 +255,3 @@ const revalidate = async ()=>{ | ||
set({ | ||
_i: _internal.UNDEFINED | ||
_i: index_js.UNDEFINED | ||
}); | ||
@@ -715,3 +261,3 @@ // return the data | ||
}, config); | ||
const mutate = React.useCallback(// eslint-disable-next-line func-names | ||
const mutate = react.useCallback(// eslint-disable-next-line func-names | ||
function(data, opts) { | ||
@@ -728,3 +274,3 @@ // When passing as a boolean, it's explicitly used to disable/enable | ||
if (shouldRevalidate) { | ||
if (!_internal.isUndefined(data)) { | ||
if (!index_js.isUndefined(data)) { | ||
// We only revalidate the pages that are changed | ||
@@ -754,8 +300,8 @@ set({ | ||
// Extend the SWR API | ||
const setSize = React.useCallback((arg)=>{ | ||
const setSize = react.useCallback((arg)=>{ | ||
// It is possible that the key is still falsy. | ||
if (!infiniteKey) return EMPTY_PROMISE; | ||
const [, changeSize] = _internal.createCacheHelper(cache, infiniteKey); | ||
const [, changeSize] = index_js.createCacheHelper(cache, infiniteKey); | ||
let size; | ||
if (_internal.isFunction(arg)) { | ||
if (index_js.isFunction(arg)) { | ||
size = arg(resolvePageSize()); | ||
@@ -772,11 +318,11 @@ } else if (typeof arg == 'number') { | ||
const data = []; | ||
const [getInfiniteCache] = _internal.createCacheHelper(cache, infiniteKey); | ||
const [getInfiniteCache] = index_js.createCacheHelper(cache, infiniteKey); | ||
let previousPageData = null; | ||
for(let i = 0; i < size; ++i){ | ||
const [pageKey] = _internal.serialize(getKey(i, previousPageData)); | ||
const [getCache] = _internal.createCacheHelper(cache, pageKey); | ||
const [pageKey] = index_js.serialize(getKey(i, previousPageData)); | ||
const [getCache] = index_js.createCacheHelper(cache, pageKey); | ||
// Get the cached page data. | ||
const pageData = pageKey ? getCache().data : _internal.UNDEFINED; | ||
const pageData = pageKey ? getCache().data : index_js.UNDEFINED; | ||
// Call `mutate` with infinte cache data if we can't get it from the page cache. | ||
if (_internal.isUndefined(pageData)) { | ||
if (index_js.isUndefined(pageData)) { | ||
return mutate(getInfiniteCache().data); | ||
@@ -816,3 +362,3 @@ } | ||
}; | ||
const useSWRInfinite = _internal.withMiddleware(useSWR, infinite); | ||
const useSWRInfinite = index_js.withMiddleware(useSWR__default.default, infinite); | ||
@@ -819,0 +365,0 @@ exports.default = useSWRInfinite; |
@@ -1,2 +0,2 @@ | ||
import { Key, Arguments, SWRResponse } from '../_internal/index.js'; | ||
import { Key, Arguments, SWRResponse } from '../index/index.js'; | ||
@@ -3,0 +3,0 @@ type FetcherResponse<Data> = Data | Promise<Data>; |
Object.defineProperty(exports, '__esModule', { value: true }); | ||
var React = require('react'); | ||
var index_js = require('use-sync-external-store/shim/index.js'); | ||
var _internal = require('swr/_internal'); | ||
var useSWR = require('../index/index.js'); | ||
var index_js = require('../_internal/index.js'); | ||
@@ -10,546 +10,5 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } | ||
var React__default = /*#__PURE__*/_interopDefault(React); | ||
var useSWR__default = /*#__PURE__*/_interopDefault(useSWR); | ||
/// <reference types="react/experimental" /> | ||
const use = React__default.default.use || // This extra generic is to avoid TypeScript mixing up the generic and JSX sytax | ||
// and emitting an error. | ||
// We assume that this is only for the `use(thenable)` case, not `use(context)`. | ||
// https://github.com/facebook/react/blob/aed00dacfb79d17c53218404c52b1c7aa59c4a89/packages/react-server/src/ReactFizzThenable.js#L45 | ||
((thenable)=>{ | ||
switch(thenable.status){ | ||
case 'pending': | ||
throw thenable; | ||
case 'fulfilled': | ||
return thenable.value; | ||
case 'rejected': | ||
throw thenable.reason; | ||
default: | ||
thenable.status = 'pending'; | ||
thenable.then((v)=>{ | ||
thenable.status = 'fulfilled'; | ||
thenable.value = v; | ||
}, (e)=>{ | ||
thenable.status = 'rejected'; | ||
thenable.reason = e; | ||
}); | ||
throw thenable; | ||
} | ||
}); | ||
const WITH_DEDUPE = { | ||
dedupe: true | ||
}; | ||
const useSWRHandler = (_key, fetcher, config)=>{ | ||
const { cache, compare, suspense, fallbackData, revalidateOnMount, revalidateIfStale, refreshInterval, refreshWhenHidden, refreshWhenOffline, keepPreviousData } = config; | ||
const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = _internal.SWRGlobalState.get(cache); | ||
// `key` is the identifier of the SWR internal state, | ||
// `fnArg` is the argument/arguments parsed from the key, which will be passed | ||
// to the fetcher. | ||
// All of them are derived from `_key`. | ||
const [key, fnArg] = _internal.serialize(_key); | ||
// If it's the initial render of this hook. | ||
const initialMountedRef = React.useRef(false); | ||
// If the hook is unmounted already. This will be used to prevent some effects | ||
// to be called after unmounting. | ||
const unmountedRef = React.useRef(false); | ||
// Refs to keep the key and config. | ||
const keyRef = React.useRef(key); | ||
const fetcherRef = React.useRef(fetcher); | ||
const configRef = React.useRef(config); | ||
const getConfig = ()=>configRef.current; | ||
const isActive = ()=>getConfig().isVisible() && getConfig().isOnline(); | ||
const [getCache, setCache, subscribeCache, getInitialCache] = _internal.createCacheHelper(cache, key); | ||
const stateDependencies = React.useRef({}).current; | ||
// Resolve the fallback data from either the inline option, or the global provider. | ||
// If it's a promise, we simply let React suspend and resolve it for us. | ||
let fallback = _internal.isUndefined(fallbackData) ? _internal.isUndefined(config.fallback) ? _internal.UNDEFINED : config.fallback[key] : fallbackData; | ||
if (fallback && _internal.isPromiseLike(fallback)) { | ||
fallback = use(fallback); | ||
} | ||
const isEqual = (prev, current)=>{ | ||
for(const _ in stateDependencies){ | ||
const t = _; | ||
if (t === 'data') { | ||
if (!compare(prev[t], current[t])) { | ||
if (!_internal.isUndefined(prev[t])) { | ||
return false; | ||
} | ||
if (!compare(returnedData, current[t])) { | ||
return false; | ||
} | ||
} | ||
} else { | ||
if (current[t] !== prev[t]) { | ||
return false; | ||
} | ||
} | ||
} | ||
return true; | ||
}; | ||
const getSnapshot = React.useMemo(()=>{ | ||
const shouldStartRequest = (()=>{ | ||
if (!key) return false; | ||
if (!fetcher) return false; | ||
// If `revalidateOnMount` is set, we take the value directly. | ||
if (!_internal.isUndefined(revalidateOnMount)) return revalidateOnMount; | ||
// If it's paused, we skip revalidation. | ||
if (getConfig().isPaused()) return false; | ||
if (suspense) return false; | ||
return revalidateIfStale !== false; | ||
})(); | ||
// Get the cache and merge it with expected states. | ||
const getSelectedCache = (state)=>{ | ||
// We only select the needed fields from the state. | ||
const snapshot = _internal.mergeObjects(state); | ||
delete snapshot._k; | ||
if (!shouldStartRequest) { | ||
return snapshot; | ||
} | ||
return { | ||
isValidating: true, | ||
isLoading: true, | ||
...snapshot | ||
}; | ||
}; | ||
const cachedData = getCache(); | ||
const initialData = getInitialCache(); | ||
const clientSnapshot = getSelectedCache(cachedData); | ||
const serverSnapshot = cachedData === initialData ? clientSnapshot : getSelectedCache(initialData); | ||
// To make sure that we are returning the same object reference to avoid | ||
// unnecessary re-renders, we keep the previous snapshot and use deep | ||
// comparison to check if we need to return a new one. | ||
let memorizedSnapshot = clientSnapshot; | ||
return [ | ||
()=>{ | ||
const newSnapshot = getSelectedCache(getCache()); | ||
const compareResult = isEqual(newSnapshot, memorizedSnapshot); | ||
if (compareResult) { | ||
// Mentally, we should always return the `memorizedSnapshot` here | ||
// as there's no change between the new and old snapshots. | ||
// However, since the `isEqual` function only compares selected fields, | ||
// the values of the unselected fields might be changed. That's | ||
// simply because we didn't track them. | ||
// To support the case in https://github.com/vercel/swr/pull/2576, | ||
// we need to update these fields in the `memorizedSnapshot` too | ||
// with direct mutations to ensure the snapshot is always up-to-date | ||
// even for the unselected fields, but only trigger re-renders when | ||
// the selected fields are changed. | ||
memorizedSnapshot.data = newSnapshot.data; | ||
memorizedSnapshot.isLoading = newSnapshot.isLoading; | ||
memorizedSnapshot.isValidating = newSnapshot.isValidating; | ||
memorizedSnapshot.error = newSnapshot.error; | ||
return memorizedSnapshot; | ||
} else { | ||
memorizedSnapshot = newSnapshot; | ||
return newSnapshot; | ||
} | ||
}, | ||
()=>serverSnapshot | ||
]; | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, [ | ||
cache, | ||
key | ||
]); | ||
// Get the current state that SWR should return. | ||
const cached = index_js.useSyncExternalStore(React.useCallback((callback)=>subscribeCache(key, (current, prev)=>{ | ||
if (!isEqual(prev, current)) callback(); | ||
}), // eslint-disable-next-line react-hooks/exhaustive-deps | ||
[ | ||
cache, | ||
key | ||
]), getSnapshot[0], getSnapshot[1]); | ||
const isInitialMount = !initialMountedRef.current; | ||
const hasRevalidator = EVENT_REVALIDATORS[key] && EVENT_REVALIDATORS[key].length > 0; | ||
const cachedData = cached.data; | ||
const data = _internal.isUndefined(cachedData) ? fallback : cachedData; | ||
const error = cached.error; | ||
// Use a ref to store previously returned data. Use the initial data as its initial value. | ||
const laggyDataRef = React.useRef(data); | ||
const returnedData = keepPreviousData ? _internal.isUndefined(cachedData) ? laggyDataRef.current : cachedData : data; | ||
// - 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. | ||
const shouldDoInitialRevalidation = (()=>{ | ||
// if a key already has revalidators and also has error, we should not trigger revalidation | ||
if (hasRevalidator && !_internal.isUndefined(error)) return false; | ||
// If `revalidateOnMount` is set, we take the value directly. | ||
if (isInitialMount && !_internal.isUndefined(revalidateOnMount)) return revalidateOnMount; | ||
// If it's paused, we skip revalidation. | ||
if (getConfig().isPaused()) return false; | ||
// Under suspense mode, it will always fetch on render if there is no | ||
// stale data so no need to revalidate immediately mount it again. | ||
// If data exists, only revalidate if `revalidateIfStale` is true. | ||
if (suspense) return _internal.isUndefined(data) ? false : revalidateIfStale; | ||
// If there is no stale data, we need to revalidate when mount; | ||
// If `revalidateIfStale` is set to true, we will always revalidate. | ||
return _internal.isUndefined(data) || revalidateIfStale; | ||
})(); | ||
// Resolve the default validating state: | ||
// If it's able to validate, and it should revalidate when mount, this will be true. | ||
const defaultValidatingState = !!(key && fetcher && isInitialMount && shouldDoInitialRevalidation); | ||
const isValidating = _internal.isUndefined(cached.isValidating) ? defaultValidatingState : cached.isValidating; | ||
const isLoading = _internal.isUndefined(cached.isLoading) ? defaultValidatingState : cached.isLoading; | ||
// The revalidation function is a carefully crafted wrapper of the original | ||
// `fetcher`, to correctly handle the many edge cases. | ||
const revalidate = React.useCallback(async (revalidateOpts)=>{ | ||
const currentFetcher = fetcherRef.current; | ||
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) { | ||
return false; | ||
} | ||
let newData; | ||
let startAt; | ||
let loading = true; | ||
const opts = revalidateOpts || {}; | ||
// If there is no ongoing concurrent request, or `dedupe` is not set, a | ||
// new request should be initiated. | ||
const shouldStartNewRequest = !FETCH[key] || !opts.dedupe; | ||
/* | ||
For React 17 | ||
Do unmount check for calls: | ||
If key has changed during the revalidation, or the component has been | ||
unmounted, old dispatch and old event callbacks should not take any | ||
effect | ||
For React 18 | ||
only check if key has changed | ||
https://github.com/reactwg/react-18/discussions/82 | ||
*/ const callbackSafeguard = ()=>{ | ||
if (_internal.IS_REACT_LEGACY) { | ||
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current; | ||
} | ||
return key === keyRef.current; | ||
}; | ||
// The final state object when the request finishes. | ||
const finalState = { | ||
isValidating: false, | ||
isLoading: false | ||
}; | ||
const finishRequestAndUpdateState = ()=>{ | ||
setCache(finalState); | ||
}; | ||
const cleanupState = ()=>{ | ||
// Check if it's still the same request before deleting it. | ||
const requestInfo = FETCH[key]; | ||
if (requestInfo && requestInfo[1] === startAt) { | ||
delete FETCH[key]; | ||
} | ||
}; | ||
// Start fetching. Change the `isValidating` state, update the cache. | ||
const initialState = { | ||
isValidating: true | ||
}; | ||
// It is in the `isLoading` state, if and only if there is no cached data. | ||
// This bypasses fallback data and laggy data. | ||
if (_internal.isUndefined(getCache().data)) { | ||
initialState.isLoading = true; | ||
} | ||
try { | ||
if (shouldStartNewRequest) { | ||
setCache(initialState); | ||
// If no cache is being rendered currently (it shows a blank page), | ||
// we trigger the loading slow event. | ||
if (config.loadingTimeout && _internal.isUndefined(getCache().data)) { | ||
setTimeout(()=>{ | ||
if (loading && callbackSafeguard()) { | ||
getConfig().onLoadingSlow(key, config); | ||
} | ||
}, config.loadingTimeout); | ||
} | ||
// Start the request and save the timestamp. | ||
// Key must be truthy if entering here. | ||
FETCH[key] = [ | ||
currentFetcher(fnArg), | ||
_internal.getTimestamp() | ||
]; | ||
} | ||
[newData, startAt] = FETCH[key]; | ||
newData = await newData; | ||
if (shouldStartNewRequest) { | ||
// If the request isn't interrupted, clean it up after the | ||
// deduplication interval. | ||
setTimeout(cleanupState, config.dedupingInterval); | ||
} | ||
// If there're other ongoing request(s), started after the current one, | ||
// we need to ignore the current one to avoid possible race conditions: | ||
// req1------------------>res1 (current one) | ||
// req2---------------->res2 | ||
// the request that fired later will always be kept. | ||
// The timestamp maybe be `undefined` or a number | ||
if (!FETCH[key] || FETCH[key][1] !== startAt) { | ||
if (shouldStartNewRequest) { | ||
if (callbackSafeguard()) { | ||
getConfig().onDiscarded(key); | ||
} | ||
} | ||
return false; | ||
} | ||
// Clear error. | ||
finalState.error = _internal.UNDEFINED; | ||
// If there're other mutations(s), that overlapped with the current revalidation: | ||
// case 1: | ||
// req------------------>res | ||
// mutate------>end | ||
// case 2: | ||
// req------------>res | ||
// mutate------>end | ||
// case 3: | ||
// req------------------>res | ||
// mutate-------...----------> | ||
// we have to ignore the revalidation result (res) because it's no longer fresh. | ||
// meanwhile, a new revalidation should be triggered when the mutation ends. | ||
const mutationInfo = MUTATION[key]; | ||
if (!_internal.isUndefined(mutationInfo) && // case 1 | ||
(startAt <= mutationInfo[0] || // case 2 | ||
startAt <= mutationInfo[1] || // case 3 | ||
mutationInfo[1] === 0)) { | ||
finishRequestAndUpdateState(); | ||
if (shouldStartNewRequest) { | ||
if (callbackSafeguard()) { | ||
getConfig().onDiscarded(key); | ||
} | ||
} | ||
return false; | ||
} | ||
// Deep compare with the latest state to avoid extra re-renders. | ||
// For local state, compare and assign. | ||
const cacheData = getCache().data; | ||
// Since the compare fn could be custom fn | ||
// cacheData might be different from newData even when compare fn returns True | ||
finalState.data = compare(cacheData, newData) ? cacheData : newData; | ||
// Trigger the successful callback if it's the original request. | ||
if (shouldStartNewRequest) { | ||
if (callbackSafeguard()) { | ||
getConfig().onSuccess(newData, key, config); | ||
} | ||
} | ||
} catch (err) { | ||
cleanupState(); | ||
const currentConfig = getConfig(); | ||
const { shouldRetryOnError } = currentConfig; | ||
// Not paused, we continue handling the error. Otherwise, discard it. | ||
if (!currentConfig.isPaused()) { | ||
// Get a new error, don't use deep comparison for errors. | ||
finalState.error = err; | ||
// Error event and retry logic. Only for the actual request, not | ||
// deduped ones. | ||
if (shouldStartNewRequest && callbackSafeguard()) { | ||
currentConfig.onError(err, key, currentConfig); | ||
if (shouldRetryOnError === true || _internal.isFunction(shouldRetryOnError) && shouldRetryOnError(err)) { | ||
if (!getConfig().revalidateOnFocus || !getConfig().revalidateOnReconnect || isActive()) { | ||
// If it's inactive, stop. It will auto-revalidate when | ||
// refocusing or reconnecting. | ||
// When retrying, deduplication is always enabled. | ||
currentConfig.onErrorRetry(err, key, currentConfig, (_opts)=>{ | ||
const revalidators = EVENT_REVALIDATORS[key]; | ||
if (revalidators && revalidators[0]) { | ||
revalidators[0](_internal.revalidateEvents.ERROR_REVALIDATE_EVENT, _opts); | ||
} | ||
}, { | ||
retryCount: (opts.retryCount || 0) + 1, | ||
dedupe: true | ||
}); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
// Mark loading as stopped. | ||
loading = false; | ||
// Update the current hook's state. | ||
finishRequestAndUpdateState(); | ||
return true; | ||
}, // `setState` is immutable, and `eventsCallback`, `fnArg`, and | ||
// `keyValidating` are depending on `key`, so we can exclude them from | ||
// the deps array. | ||
// | ||
// FIXME: | ||
// `fn` and `config` might be changed during the lifecycle, | ||
// but they might be changed every render like this. | ||
// `useSWR('key', () => fetch('/api/'), { suspense: true })` | ||
// So we omit the values from the deps array | ||
// even though it might cause unexpected behaviors. | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
[ | ||
key, | ||
cache | ||
]); | ||
// Similar to the global mutate but bound to the current cache and key. | ||
// `cache` isn't allowed to change during the lifecycle. | ||
const boundMutate = React.useCallback(// Use callback to make sure `keyRef.current` returns latest result every time | ||
(...args)=>{ | ||
return _internal.internalMutate(cache, keyRef.current, ...args); | ||
}, // eslint-disable-next-line react-hooks/exhaustive-deps | ||
[]); | ||
// The logic for updating refs. | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
fetcherRef.current = fetcher; | ||
configRef.current = config; | ||
// Handle laggy data updates. If there's cached data of the current key, | ||
// it'll be the correct reference. | ||
if (!_internal.isUndefined(cachedData)) { | ||
laggyDataRef.current = cachedData; | ||
} | ||
}); | ||
// After mounted or key changed. | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
if (!key) return; | ||
const softRevalidate = revalidate.bind(_internal.UNDEFINED, WITH_DEDUPE); | ||
// Expose revalidators to global event listeners. So we can trigger | ||
// revalidation from the outside. | ||
let nextFocusRevalidatedAt = 0; | ||
const onRevalidate = (type, opts = {})=>{ | ||
if (type == _internal.revalidateEvents.FOCUS_EVENT) { | ||
const now = Date.now(); | ||
if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) { | ||
nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval; | ||
softRevalidate(); | ||
} | ||
} else if (type == _internal.revalidateEvents.RECONNECT_EVENT) { | ||
if (getConfig().revalidateOnReconnect && isActive()) { | ||
softRevalidate(); | ||
} | ||
} else if (type == _internal.revalidateEvents.MUTATE_EVENT) { | ||
return revalidate(); | ||
} else if (type == _internal.revalidateEvents.ERROR_REVALIDATE_EVENT) { | ||
return revalidate(opts); | ||
} | ||
return; | ||
}; | ||
const unsubEvents = _internal.subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate); | ||
// Mark the component as mounted and update corresponding refs. | ||
unmountedRef.current = false; | ||
keyRef.current = key; | ||
initialMountedRef.current = true; | ||
// Keep the original key in the cache. | ||
setCache({ | ||
_k: fnArg | ||
}); | ||
// Trigger a revalidation | ||
if (shouldDoInitialRevalidation) { | ||
if (_internal.isUndefined(data) || _internal.IS_SERVER) { | ||
// Revalidate immediately. | ||
softRevalidate(); | ||
} else { | ||
// Delay the revalidate if we have data to return so we won't block | ||
// rendering. | ||
_internal.rAF(softRevalidate); | ||
} | ||
} | ||
return ()=>{ | ||
// Mark it as unmounted. | ||
unmountedRef.current = true; | ||
unsubEvents(); | ||
}; | ||
}, [ | ||
key | ||
]); | ||
// Polling | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
let timer; | ||
function next() { | ||
// Use the passed interval | ||
// ...or invoke the function with the updated data to get the interval | ||
const interval = _internal.isFunction(refreshInterval) ? refreshInterval(getCache().data) : refreshInterval; | ||
// We only start the next interval if `refreshInterval` is not 0, and: | ||
// - `force` is true, which is the start of polling | ||
// - or `timer` is not 0, which means the effect wasn't canceled | ||
if (interval && timer !== -1) { | ||
timer = setTimeout(execute, interval); | ||
} | ||
} | ||
function execute() { | ||
// Check if it's OK to execute: | ||
// Only revalidate when the page is visible, online, and not errored. | ||
if (!getCache().error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) { | ||
revalidate(WITH_DEDUPE).then(next); | ||
} else { | ||
// Schedule the next interval to check again. | ||
next(); | ||
} | ||
} | ||
next(); | ||
return ()=>{ | ||
if (timer) { | ||
clearTimeout(timer); | ||
timer = -1; | ||
} | ||
}; | ||
}, [ | ||
refreshInterval, | ||
refreshWhenHidden, | ||
refreshWhenOffline, | ||
key | ||
]); | ||
// Display debug info in React DevTools. | ||
React.useDebugValue(returnedData); | ||
// In Suspense mode, we can't return the empty `data` state. | ||
// If there is an `error`, the `error` needs to be thrown to the error boundary. | ||
// If there is no `error`, the `revalidation` promise needs to be thrown to | ||
// the suspense boundary. | ||
if (suspense && _internal.isUndefined(data) && key) { | ||
// SWR should throw when trying to use Suspense on the server with React 18, | ||
// without providing any fallback data. This causes hydration errors. See: | ||
// https://github.com/vercel/swr/issues/1832 | ||
if (!_internal.IS_REACT_LEGACY && _internal.IS_SERVER) { | ||
throw new Error('Fallback data is required when using Suspense in SSR.'); | ||
} | ||
// Always update fetcher and config refs even with the Suspense mode. | ||
fetcherRef.current = fetcher; | ||
configRef.current = config; | ||
unmountedRef.current = false; | ||
const req = PRELOAD[key]; | ||
if (!_internal.isUndefined(req)) { | ||
const promise = boundMutate(req); | ||
use(promise); | ||
} | ||
if (_internal.isUndefined(error)) { | ||
const promise = revalidate(WITH_DEDUPE); | ||
if (!_internal.isUndefined(returnedData)) { | ||
promise.status = 'fulfilled'; | ||
promise.value = true; | ||
} | ||
use(promise); | ||
} else { | ||
throw error; | ||
} | ||
} | ||
return { | ||
mutate: boundMutate, | ||
get data () { | ||
stateDependencies.data = true; | ||
return returnedData; | ||
}, | ||
get error () { | ||
stateDependencies.error = true; | ||
return error; | ||
}, | ||
get isValidating () { | ||
stateDependencies.isValidating = true; | ||
return isValidating; | ||
}, | ||
get isLoading () { | ||
stateDependencies.isLoading = true; | ||
return isLoading; | ||
} | ||
}; | ||
}; | ||
_internal.OBJECT.defineProperty(_internal.SWRConfig, 'defaultValue', { | ||
value: _internal.defaultConfig | ||
}); | ||
/** | ||
* A hook to fetch data. | ||
* | ||
* @link https://swr.vercel.app | ||
* @example | ||
* ```jsx | ||
* import useSWR from 'swr' | ||
* function Profile() { | ||
* const { data, error, isLoading } = useSWR('/api/user', fetcher) | ||
* if (error) return <div>failed to load</div> | ||
* if (isLoading) return <div>loading...</div> | ||
* return <div>hello {data.name}!</div> | ||
* } | ||
* ``` | ||
*/ const useSWR = _internal.withArgs(useSWRHandler); | ||
const startTransition = _internal.IS_REACT_LEGACY ? (cb)=>{ | ||
const startTransition = index_js.IS_REACT_LEGACY ? (cb)=>{ | ||
cb(); | ||
@@ -608,3 +67,3 @@ } : React__default.default.startTransition; | ||
}, []); | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
index_js.useIsomorphicLayoutEffect(()=>{ | ||
unmountedRef.current = false; | ||
@@ -623,3 +82,3 @@ return ()=>{ | ||
const mutation = ()=>(key, fetcher, config = {})=>{ | ||
const { mutate } = _internal.useSWRConfig(); | ||
const { mutate } = useSWR.useSWRConfig(); | ||
const keyRef = React.useRef(key); | ||
@@ -631,4 +90,4 @@ const fetcherRef = React.useRef(fetcher); | ||
const [stateRef, stateDependencies, setState] = useStateWithDeps({ | ||
data: _internal.UNDEFINED, | ||
error: _internal.UNDEFINED, | ||
data: index_js.UNDEFINED, | ||
error: index_js.UNDEFINED, | ||
isMutating: false | ||
@@ -638,3 +97,3 @@ }); | ||
const trigger = React.useCallback(async (arg, opts)=>{ | ||
const [serializedKey, resolvedKey] = _internal.serialize(keyRef.current); | ||
const [serializedKey, resolvedKey] = index_js.serialize(keyRef.current); | ||
if (!fetcherRef.current) { | ||
@@ -647,3 +106,3 @@ throw new Error('Can’t trigger the mutation: missing fetcher.'); | ||
// Disable cache population by default. | ||
const options = _internal.mergeObjects(_internal.mergeObjects({ | ||
const options = index_js.mergeObjects(index_js.mergeObjects({ | ||
populateCache: false, | ||
@@ -654,3 +113,3 @@ throwOnError: true | ||
// earlier this timestamp should be ignored. | ||
const mutationStartedAt = _internal.getTimestamp(); | ||
const mutationStartedAt = index_js.getTimestamp(); | ||
ditchMutationsUntilRef.current = mutationStartedAt; | ||
@@ -664,3 +123,3 @@ setState({ | ||
}), // We must throw the error here so we can catch and update the states. | ||
_internal.mergeObjects(options, { | ||
index_js.mergeObjects(options, { | ||
throwOnError: true | ||
@@ -695,6 +154,6 @@ })); | ||
const reset = React.useCallback(()=>{ | ||
ditchMutationsUntilRef.current = _internal.getTimestamp(); | ||
ditchMutationsUntilRef.current = index_js.getTimestamp(); | ||
setState({ | ||
data: _internal.UNDEFINED, | ||
error: _internal.UNDEFINED, | ||
data: index_js.UNDEFINED, | ||
error: index_js.UNDEFINED, | ||
isMutating: false | ||
@@ -704,3 +163,3 @@ }); | ||
}, []); | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
index_js.useIsomorphicLayoutEffect(()=>{ | ||
keyRef.current = key; | ||
@@ -746,4 +205,4 @@ fetcherRef.current = fetcher; | ||
* ``` | ||
*/ const useSWRMutation = _internal.withMiddleware(useSWR, mutation); | ||
*/ const useSWRMutation = index_js.withMiddleware(useSWR__default.default, mutation); | ||
exports.default = useSWRMutation; |
@@ -1,2 +0,2 @@ | ||
import { MutatorCallback, Key, SWRConfiguration, Middleware } from '../_internal/index.js'; | ||
import { MutatorCallback, Key, SWRConfiguration, Middleware } from '../index/index.js'; | ||
@@ -3,0 +3,0 @@ type SWRSubscriptionOptions<Data = any, Error = any> = { |
Object.defineProperty(exports, '__esModule', { value: true }); | ||
var React = require('react'); | ||
var index_js = require('use-sync-external-store/shim/index.js'); | ||
var _internal = require('swr/_internal'); | ||
var useSWR = require('../index/index.js'); | ||
var index_js = require('../_internal/index.js'); | ||
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } | ||
var React__default = /*#__PURE__*/_interopDefault(React); | ||
var useSWR__default = /*#__PURE__*/_interopDefault(useSWR); | ||
/// <reference types="react/experimental" /> | ||
const use = React__default.default.use || // This extra generic is to avoid TypeScript mixing up the generic and JSX sytax | ||
// and emitting an error. | ||
// We assume that this is only for the `use(thenable)` case, not `use(context)`. | ||
// https://github.com/facebook/react/blob/aed00dacfb79d17c53218404c52b1c7aa59c4a89/packages/react-server/src/ReactFizzThenable.js#L45 | ||
((thenable)=>{ | ||
switch(thenable.status){ | ||
case 'pending': | ||
throw thenable; | ||
case 'fulfilled': | ||
return thenable.value; | ||
case 'rejected': | ||
throw thenable.reason; | ||
default: | ||
thenable.status = 'pending'; | ||
thenable.then((v)=>{ | ||
thenable.status = 'fulfilled'; | ||
thenable.value = v; | ||
}, (e)=>{ | ||
thenable.status = 'rejected'; | ||
thenable.reason = e; | ||
}); | ||
throw thenable; | ||
} | ||
}); | ||
const WITH_DEDUPE = { | ||
dedupe: true | ||
}; | ||
const useSWRHandler = (_key, fetcher, config)=>{ | ||
const { cache, compare, suspense, fallbackData, revalidateOnMount, revalidateIfStale, refreshInterval, refreshWhenHidden, refreshWhenOffline, keepPreviousData } = config; | ||
const [EVENT_REVALIDATORS, MUTATION, FETCH, PRELOAD] = _internal.SWRGlobalState.get(cache); | ||
// `key` is the identifier of the SWR internal state, | ||
// `fnArg` is the argument/arguments parsed from the key, which will be passed | ||
// to the fetcher. | ||
// All of them are derived from `_key`. | ||
const [key, fnArg] = _internal.serialize(_key); | ||
// If it's the initial render of this hook. | ||
const initialMountedRef = React.useRef(false); | ||
// If the hook is unmounted already. This will be used to prevent some effects | ||
// to be called after unmounting. | ||
const unmountedRef = React.useRef(false); | ||
// Refs to keep the key and config. | ||
const keyRef = React.useRef(key); | ||
const fetcherRef = React.useRef(fetcher); | ||
const configRef = React.useRef(config); | ||
const getConfig = ()=>configRef.current; | ||
const isActive = ()=>getConfig().isVisible() && getConfig().isOnline(); | ||
const [getCache, setCache, subscribeCache, getInitialCache] = _internal.createCacheHelper(cache, key); | ||
const stateDependencies = React.useRef({}).current; | ||
// Resolve the fallback data from either the inline option, or the global provider. | ||
// If it's a promise, we simply let React suspend and resolve it for us. | ||
let fallback = _internal.isUndefined(fallbackData) ? _internal.isUndefined(config.fallback) ? _internal.UNDEFINED : config.fallback[key] : fallbackData; | ||
if (fallback && _internal.isPromiseLike(fallback)) { | ||
fallback = use(fallback); | ||
} | ||
const isEqual = (prev, current)=>{ | ||
for(const _ in stateDependencies){ | ||
const t = _; | ||
if (t === 'data') { | ||
if (!compare(prev[t], current[t])) { | ||
if (!_internal.isUndefined(prev[t])) { | ||
return false; | ||
} | ||
if (!compare(returnedData, current[t])) { | ||
return false; | ||
} | ||
} | ||
} else { | ||
if (current[t] !== prev[t]) { | ||
return false; | ||
} | ||
} | ||
} | ||
return true; | ||
}; | ||
const getSnapshot = React.useMemo(()=>{ | ||
const shouldStartRequest = (()=>{ | ||
if (!key) return false; | ||
if (!fetcher) return false; | ||
// If `revalidateOnMount` is set, we take the value directly. | ||
if (!_internal.isUndefined(revalidateOnMount)) return revalidateOnMount; | ||
// If it's paused, we skip revalidation. | ||
if (getConfig().isPaused()) return false; | ||
if (suspense) return false; | ||
return revalidateIfStale !== false; | ||
})(); | ||
// Get the cache and merge it with expected states. | ||
const getSelectedCache = (state)=>{ | ||
// We only select the needed fields from the state. | ||
const snapshot = _internal.mergeObjects(state); | ||
delete snapshot._k; | ||
if (!shouldStartRequest) { | ||
return snapshot; | ||
} | ||
return { | ||
isValidating: true, | ||
isLoading: true, | ||
...snapshot | ||
}; | ||
}; | ||
const cachedData = getCache(); | ||
const initialData = getInitialCache(); | ||
const clientSnapshot = getSelectedCache(cachedData); | ||
const serverSnapshot = cachedData === initialData ? clientSnapshot : getSelectedCache(initialData); | ||
// To make sure that we are returning the same object reference to avoid | ||
// unnecessary re-renders, we keep the previous snapshot and use deep | ||
// comparison to check if we need to return a new one. | ||
let memorizedSnapshot = clientSnapshot; | ||
return [ | ||
()=>{ | ||
const newSnapshot = getSelectedCache(getCache()); | ||
const compareResult = isEqual(newSnapshot, memorizedSnapshot); | ||
if (compareResult) { | ||
// Mentally, we should always return the `memorizedSnapshot` here | ||
// as there's no change between the new and old snapshots. | ||
// However, since the `isEqual` function only compares selected fields, | ||
// the values of the unselected fields might be changed. That's | ||
// simply because we didn't track them. | ||
// To support the case in https://github.com/vercel/swr/pull/2576, | ||
// we need to update these fields in the `memorizedSnapshot` too | ||
// with direct mutations to ensure the snapshot is always up-to-date | ||
// even for the unselected fields, but only trigger re-renders when | ||
// the selected fields are changed. | ||
memorizedSnapshot.data = newSnapshot.data; | ||
memorizedSnapshot.isLoading = newSnapshot.isLoading; | ||
memorizedSnapshot.isValidating = newSnapshot.isValidating; | ||
memorizedSnapshot.error = newSnapshot.error; | ||
return memorizedSnapshot; | ||
} else { | ||
memorizedSnapshot = newSnapshot; | ||
return newSnapshot; | ||
} | ||
}, | ||
()=>serverSnapshot | ||
]; | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, [ | ||
cache, | ||
key | ||
]); | ||
// Get the current state that SWR should return. | ||
const cached = index_js.useSyncExternalStore(React.useCallback((callback)=>subscribeCache(key, (current, prev)=>{ | ||
if (!isEqual(prev, current)) callback(); | ||
}), // eslint-disable-next-line react-hooks/exhaustive-deps | ||
[ | ||
cache, | ||
key | ||
]), getSnapshot[0], getSnapshot[1]); | ||
const isInitialMount = !initialMountedRef.current; | ||
const hasRevalidator = EVENT_REVALIDATORS[key] && EVENT_REVALIDATORS[key].length > 0; | ||
const cachedData = cached.data; | ||
const data = _internal.isUndefined(cachedData) ? fallback : cachedData; | ||
const error = cached.error; | ||
// Use a ref to store previously returned data. Use the initial data as its initial value. | ||
const laggyDataRef = React.useRef(data); | ||
const returnedData = keepPreviousData ? _internal.isUndefined(cachedData) ? laggyDataRef.current : cachedData : data; | ||
// - 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. | ||
const shouldDoInitialRevalidation = (()=>{ | ||
// if a key already has revalidators and also has error, we should not trigger revalidation | ||
if (hasRevalidator && !_internal.isUndefined(error)) return false; | ||
// If `revalidateOnMount` is set, we take the value directly. | ||
if (isInitialMount && !_internal.isUndefined(revalidateOnMount)) return revalidateOnMount; | ||
// If it's paused, we skip revalidation. | ||
if (getConfig().isPaused()) return false; | ||
// Under suspense mode, it will always fetch on render if there is no | ||
// stale data so no need to revalidate immediately mount it again. | ||
// If data exists, only revalidate if `revalidateIfStale` is true. | ||
if (suspense) return _internal.isUndefined(data) ? false : revalidateIfStale; | ||
// If there is no stale data, we need to revalidate when mount; | ||
// If `revalidateIfStale` is set to true, we will always revalidate. | ||
return _internal.isUndefined(data) || revalidateIfStale; | ||
})(); | ||
// Resolve the default validating state: | ||
// If it's able to validate, and it should revalidate when mount, this will be true. | ||
const defaultValidatingState = !!(key && fetcher && isInitialMount && shouldDoInitialRevalidation); | ||
const isValidating = _internal.isUndefined(cached.isValidating) ? defaultValidatingState : cached.isValidating; | ||
const isLoading = _internal.isUndefined(cached.isLoading) ? defaultValidatingState : cached.isLoading; | ||
// The revalidation function is a carefully crafted wrapper of the original | ||
// `fetcher`, to correctly handle the many edge cases. | ||
const revalidate = React.useCallback(async (revalidateOpts)=>{ | ||
const currentFetcher = fetcherRef.current; | ||
if (!key || !currentFetcher || unmountedRef.current || getConfig().isPaused()) { | ||
return false; | ||
} | ||
let newData; | ||
let startAt; | ||
let loading = true; | ||
const opts = revalidateOpts || {}; | ||
// If there is no ongoing concurrent request, or `dedupe` is not set, a | ||
// new request should be initiated. | ||
const shouldStartNewRequest = !FETCH[key] || !opts.dedupe; | ||
/* | ||
For React 17 | ||
Do unmount check for calls: | ||
If key has changed during the revalidation, or the component has been | ||
unmounted, old dispatch and old event callbacks should not take any | ||
effect | ||
For React 18 | ||
only check if key has changed | ||
https://github.com/reactwg/react-18/discussions/82 | ||
*/ const callbackSafeguard = ()=>{ | ||
if (_internal.IS_REACT_LEGACY) { | ||
return !unmountedRef.current && key === keyRef.current && initialMountedRef.current; | ||
} | ||
return key === keyRef.current; | ||
}; | ||
// The final state object when the request finishes. | ||
const finalState = { | ||
isValidating: false, | ||
isLoading: false | ||
}; | ||
const finishRequestAndUpdateState = ()=>{ | ||
setCache(finalState); | ||
}; | ||
const cleanupState = ()=>{ | ||
// Check if it's still the same request before deleting it. | ||
const requestInfo = FETCH[key]; | ||
if (requestInfo && requestInfo[1] === startAt) { | ||
delete FETCH[key]; | ||
} | ||
}; | ||
// Start fetching. Change the `isValidating` state, update the cache. | ||
const initialState = { | ||
isValidating: true | ||
}; | ||
// It is in the `isLoading` state, if and only if there is no cached data. | ||
// This bypasses fallback data and laggy data. | ||
if (_internal.isUndefined(getCache().data)) { | ||
initialState.isLoading = true; | ||
} | ||
try { | ||
if (shouldStartNewRequest) { | ||
setCache(initialState); | ||
// If no cache is being rendered currently (it shows a blank page), | ||
// we trigger the loading slow event. | ||
if (config.loadingTimeout && _internal.isUndefined(getCache().data)) { | ||
setTimeout(()=>{ | ||
if (loading && callbackSafeguard()) { | ||
getConfig().onLoadingSlow(key, config); | ||
} | ||
}, config.loadingTimeout); | ||
} | ||
// Start the request and save the timestamp. | ||
// Key must be truthy if entering here. | ||
FETCH[key] = [ | ||
currentFetcher(fnArg), | ||
_internal.getTimestamp() | ||
]; | ||
} | ||
[newData, startAt] = FETCH[key]; | ||
newData = await newData; | ||
if (shouldStartNewRequest) { | ||
// If the request isn't interrupted, clean it up after the | ||
// deduplication interval. | ||
setTimeout(cleanupState, config.dedupingInterval); | ||
} | ||
// If there're other ongoing request(s), started after the current one, | ||
// we need to ignore the current one to avoid possible race conditions: | ||
// req1------------------>res1 (current one) | ||
// req2---------------->res2 | ||
// the request that fired later will always be kept. | ||
// The timestamp maybe be `undefined` or a number | ||
if (!FETCH[key] || FETCH[key][1] !== startAt) { | ||
if (shouldStartNewRequest) { | ||
if (callbackSafeguard()) { | ||
getConfig().onDiscarded(key); | ||
} | ||
} | ||
return false; | ||
} | ||
// Clear error. | ||
finalState.error = _internal.UNDEFINED; | ||
// If there're other mutations(s), that overlapped with the current revalidation: | ||
// case 1: | ||
// req------------------>res | ||
// mutate------>end | ||
// case 2: | ||
// req------------>res | ||
// mutate------>end | ||
// case 3: | ||
// req------------------>res | ||
// mutate-------...----------> | ||
// we have to ignore the revalidation result (res) because it's no longer fresh. | ||
// meanwhile, a new revalidation should be triggered when the mutation ends. | ||
const mutationInfo = MUTATION[key]; | ||
if (!_internal.isUndefined(mutationInfo) && // case 1 | ||
(startAt <= mutationInfo[0] || // case 2 | ||
startAt <= mutationInfo[1] || // case 3 | ||
mutationInfo[1] === 0)) { | ||
finishRequestAndUpdateState(); | ||
if (shouldStartNewRequest) { | ||
if (callbackSafeguard()) { | ||
getConfig().onDiscarded(key); | ||
} | ||
} | ||
return false; | ||
} | ||
// Deep compare with the latest state to avoid extra re-renders. | ||
// For local state, compare and assign. | ||
const cacheData = getCache().data; | ||
// Since the compare fn could be custom fn | ||
// cacheData might be different from newData even when compare fn returns True | ||
finalState.data = compare(cacheData, newData) ? cacheData : newData; | ||
// Trigger the successful callback if it's the original request. | ||
if (shouldStartNewRequest) { | ||
if (callbackSafeguard()) { | ||
getConfig().onSuccess(newData, key, config); | ||
} | ||
} | ||
} catch (err) { | ||
cleanupState(); | ||
const currentConfig = getConfig(); | ||
const { shouldRetryOnError } = currentConfig; | ||
// Not paused, we continue handling the error. Otherwise, discard it. | ||
if (!currentConfig.isPaused()) { | ||
// Get a new error, don't use deep comparison for errors. | ||
finalState.error = err; | ||
// Error event and retry logic. Only for the actual request, not | ||
// deduped ones. | ||
if (shouldStartNewRequest && callbackSafeguard()) { | ||
currentConfig.onError(err, key, currentConfig); | ||
if (shouldRetryOnError === true || _internal.isFunction(shouldRetryOnError) && shouldRetryOnError(err)) { | ||
if (!getConfig().revalidateOnFocus || !getConfig().revalidateOnReconnect || isActive()) { | ||
// If it's inactive, stop. It will auto-revalidate when | ||
// refocusing or reconnecting. | ||
// When retrying, deduplication is always enabled. | ||
currentConfig.onErrorRetry(err, key, currentConfig, (_opts)=>{ | ||
const revalidators = EVENT_REVALIDATORS[key]; | ||
if (revalidators && revalidators[0]) { | ||
revalidators[0](_internal.revalidateEvents.ERROR_REVALIDATE_EVENT, _opts); | ||
} | ||
}, { | ||
retryCount: (opts.retryCount || 0) + 1, | ||
dedupe: true | ||
}); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
// Mark loading as stopped. | ||
loading = false; | ||
// Update the current hook's state. | ||
finishRequestAndUpdateState(); | ||
return true; | ||
}, // `setState` is immutable, and `eventsCallback`, `fnArg`, and | ||
// `keyValidating` are depending on `key`, so we can exclude them from | ||
// the deps array. | ||
// | ||
// FIXME: | ||
// `fn` and `config` might be changed during the lifecycle, | ||
// but they might be changed every render like this. | ||
// `useSWR('key', () => fetch('/api/'), { suspense: true })` | ||
// So we omit the values from the deps array | ||
// even though it might cause unexpected behaviors. | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
[ | ||
key, | ||
cache | ||
]); | ||
// Similar to the global mutate but bound to the current cache and key. | ||
// `cache` isn't allowed to change during the lifecycle. | ||
const boundMutate = React.useCallback(// Use callback to make sure `keyRef.current` returns latest result every time | ||
(...args)=>{ | ||
return _internal.internalMutate(cache, keyRef.current, ...args); | ||
}, // eslint-disable-next-line react-hooks/exhaustive-deps | ||
[]); | ||
// The logic for updating refs. | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
fetcherRef.current = fetcher; | ||
configRef.current = config; | ||
// Handle laggy data updates. If there's cached data of the current key, | ||
// it'll be the correct reference. | ||
if (!_internal.isUndefined(cachedData)) { | ||
laggyDataRef.current = cachedData; | ||
} | ||
}); | ||
// After mounted or key changed. | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
if (!key) return; | ||
const softRevalidate = revalidate.bind(_internal.UNDEFINED, WITH_DEDUPE); | ||
// Expose revalidators to global event listeners. So we can trigger | ||
// revalidation from the outside. | ||
let nextFocusRevalidatedAt = 0; | ||
const onRevalidate = (type, opts = {})=>{ | ||
if (type == _internal.revalidateEvents.FOCUS_EVENT) { | ||
const now = Date.now(); | ||
if (getConfig().revalidateOnFocus && now > nextFocusRevalidatedAt && isActive()) { | ||
nextFocusRevalidatedAt = now + getConfig().focusThrottleInterval; | ||
softRevalidate(); | ||
} | ||
} else if (type == _internal.revalidateEvents.RECONNECT_EVENT) { | ||
if (getConfig().revalidateOnReconnect && isActive()) { | ||
softRevalidate(); | ||
} | ||
} else if (type == _internal.revalidateEvents.MUTATE_EVENT) { | ||
return revalidate(); | ||
} else if (type == _internal.revalidateEvents.ERROR_REVALIDATE_EVENT) { | ||
return revalidate(opts); | ||
} | ||
return; | ||
}; | ||
const unsubEvents = _internal.subscribeCallback(key, EVENT_REVALIDATORS, onRevalidate); | ||
// Mark the component as mounted and update corresponding refs. | ||
unmountedRef.current = false; | ||
keyRef.current = key; | ||
initialMountedRef.current = true; | ||
// Keep the original key in the cache. | ||
setCache({ | ||
_k: fnArg | ||
}); | ||
// Trigger a revalidation | ||
if (shouldDoInitialRevalidation) { | ||
if (_internal.isUndefined(data) || _internal.IS_SERVER) { | ||
// Revalidate immediately. | ||
softRevalidate(); | ||
} else { | ||
// Delay the revalidate if we have data to return so we won't block | ||
// rendering. | ||
_internal.rAF(softRevalidate); | ||
} | ||
} | ||
return ()=>{ | ||
// Mark it as unmounted. | ||
unmountedRef.current = true; | ||
unsubEvents(); | ||
}; | ||
}, [ | ||
key | ||
]); | ||
// Polling | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
let timer; | ||
function next() { | ||
// Use the passed interval | ||
// ...or invoke the function with the updated data to get the interval | ||
const interval = _internal.isFunction(refreshInterval) ? refreshInterval(getCache().data) : refreshInterval; | ||
// We only start the next interval if `refreshInterval` is not 0, and: | ||
// - `force` is true, which is the start of polling | ||
// - or `timer` is not 0, which means the effect wasn't canceled | ||
if (interval && timer !== -1) { | ||
timer = setTimeout(execute, interval); | ||
} | ||
} | ||
function execute() { | ||
// Check if it's OK to execute: | ||
// Only revalidate when the page is visible, online, and not errored. | ||
if (!getCache().error && (refreshWhenHidden || getConfig().isVisible()) && (refreshWhenOffline || getConfig().isOnline())) { | ||
revalidate(WITH_DEDUPE).then(next); | ||
} else { | ||
// Schedule the next interval to check again. | ||
next(); | ||
} | ||
} | ||
next(); | ||
return ()=>{ | ||
if (timer) { | ||
clearTimeout(timer); | ||
timer = -1; | ||
} | ||
}; | ||
}, [ | ||
refreshInterval, | ||
refreshWhenHidden, | ||
refreshWhenOffline, | ||
key | ||
]); | ||
// Display debug info in React DevTools. | ||
React.useDebugValue(returnedData); | ||
// In Suspense mode, we can't return the empty `data` state. | ||
// If there is an `error`, the `error` needs to be thrown to the error boundary. | ||
// If there is no `error`, the `revalidation` promise needs to be thrown to | ||
// the suspense boundary. | ||
if (suspense && _internal.isUndefined(data) && key) { | ||
// SWR should throw when trying to use Suspense on the server with React 18, | ||
// without providing any fallback data. This causes hydration errors. See: | ||
// https://github.com/vercel/swr/issues/1832 | ||
if (!_internal.IS_REACT_LEGACY && _internal.IS_SERVER) { | ||
throw new Error('Fallback data is required when using Suspense in SSR.'); | ||
} | ||
// Always update fetcher and config refs even with the Suspense mode. | ||
fetcherRef.current = fetcher; | ||
configRef.current = config; | ||
unmountedRef.current = false; | ||
const req = PRELOAD[key]; | ||
if (!_internal.isUndefined(req)) { | ||
const promise = boundMutate(req); | ||
use(promise); | ||
} | ||
if (_internal.isUndefined(error)) { | ||
const promise = revalidate(WITH_DEDUPE); | ||
if (!_internal.isUndefined(returnedData)) { | ||
promise.status = 'fulfilled'; | ||
promise.value = true; | ||
} | ||
use(promise); | ||
} else { | ||
throw error; | ||
} | ||
} | ||
return { | ||
mutate: boundMutate, | ||
get data () { | ||
stateDependencies.data = true; | ||
return returnedData; | ||
}, | ||
get error () { | ||
stateDependencies.error = true; | ||
return error; | ||
}, | ||
get isValidating () { | ||
stateDependencies.isValidating = true; | ||
return isValidating; | ||
}, | ||
get isLoading () { | ||
stateDependencies.isLoading = true; | ||
return isLoading; | ||
} | ||
}; | ||
}; | ||
_internal.OBJECT.defineProperty(_internal.SWRConfig, 'defaultValue', { | ||
value: _internal.defaultConfig | ||
}); | ||
/** | ||
* A hook to fetch data. | ||
* | ||
* @link https://swr.vercel.app | ||
* @example | ||
* ```jsx | ||
* import useSWR from 'swr' | ||
* function Profile() { | ||
* const { data, error, isLoading } = useSWR('/api/user', fetcher) | ||
* if (error) return <div>failed to load</div> | ||
* if (isLoading) return <div>loading...</div> | ||
* return <div>hello {data.name}!</div> | ||
* } | ||
* ``` | ||
*/ const useSWR = _internal.withArgs(useSWRHandler); | ||
const subscriptionStorage = new WeakMap(); | ||
const SUBSCRIPTION_PREFIX = '$sub$'; | ||
const subscription = (useSWRNext)=>(_key, subscribe, config)=>{ | ||
const [key, args] = _internal.serialize(_key); | ||
const [key, args] = index_js.serialize(_key); | ||
// Prefix the key to avoid conflicts with other SWR resources. | ||
@@ -571,5 +28,5 @@ const subscriptionKey = key ? SUBSCRIPTION_PREFIX + key : undefined; | ||
const [subscriptions, disposers] = subscriptionStorage.get(cache); | ||
_internal.useIsomorphicLayoutEffect(()=>{ | ||
index_js.useIsomorphicLayoutEffect(()=>{ | ||
if (!subscriptionKey) return; | ||
const [, set] = _internal.createCacheHelper(cache, subscriptionKey); | ||
const [, set] = index_js.createCacheHelper(cache, subscriptionKey); | ||
const refCount = subscriptions.get(subscriptionKey) || 0; | ||
@@ -636,5 +93,5 @@ const next = (error, data)=>{ | ||
* ``` | ||
*/ const useSWRSubscription = _internal.withMiddleware(useSWR, subscription); | ||
*/ const useSWRSubscription = index_js.withMiddleware(useSWR__default.default, subscription); | ||
exports.default = useSWRSubscription; | ||
exports.subscription = subscription; |
{ | ||
"name": "swr", | ||
"version": "2.2.6-beta.4", | ||
"version": "2.2.6-beta.5", | ||
"description": "React Hooks library for remote data fetching", | ||
@@ -14,5 +14,5 @@ "keywords": [ | ||
"packageManager": "pnpm@8.4.0", | ||
"main": "./dist/core/index.js", | ||
"module": "./dist/core/index.mjs", | ||
"types": "./dist/core/index.d.ts", | ||
"main": "./dist/index/index.js", | ||
"module": "./dist/index/index.mjs", | ||
"types": "./dist/index/index.d.ts", | ||
"sideEffects": false, | ||
@@ -22,10 +22,10 @@ "exports": { | ||
".": { | ||
"react-server": "./dist/core/react-server.mjs", | ||
"react-server": "./dist/index/react-server.mjs", | ||
"import": { | ||
"types": "./dist/core/index.d.mts", | ||
"default": "./dist/core/index.mjs" | ||
"types": "./dist/index/index.d.mts", | ||
"default": "./dist/index/index.mjs" | ||
}, | ||
"require": { | ||
"types": "./dist/core/index.d.ts", | ||
"default": "./dist/core/index.js" | ||
"types": "./dist/index/index.d.ts", | ||
"default": "./dist/index/index.js" | ||
} | ||
@@ -126,4 +126,5 @@ }, | ||
"devDependencies": { | ||
"@edge-runtime/jest-environment": "^3.0.4", | ||
"@arethetypeswrong/cli": "^0.15.3", | ||
"@playwright/test": "^1.34.3", | ||
"@playwright/test": "1.34.3", | ||
"@swc/core": "^1.3.62", | ||
@@ -140,3 +141,3 @@ "@swc/jest": "0.2.26", | ||
"@typescript-eslint/parser": "5.59.8", | ||
"bunchee": "^5.1.1", | ||
"bunchee": "^6.0.2", | ||
"eslint": "8.42.0", | ||
@@ -152,3 +153,3 @@ "eslint-config-prettier": "8.8.0", | ||
"lint-staged": "13.2.2", | ||
"next": "14.1.4", | ||
"next": "15.0.4", | ||
"prettier": "2.8.8", | ||
@@ -164,3 +165,3 @@ "react": "^18.2.0", | ||
"peerDependencies": { | ||
"react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0-0" | ||
"react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" | ||
}, | ||
@@ -177,4 +178,4 @@ "prettier": { | ||
"dequal": "^2.0.3", | ||
"use-sync-external-store": "^1.2.0" | ||
"use-sync-external-store": "^1.4.0" | ||
} | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
40
262994
34
5007
1