Comparing version 2.0.0-beta.3 to 2.0.0-beta.4
@@ -21,2 +21,3 @@ import SWRConfig from './utils/config-context'; | ||
export { withMiddleware } from './utils/with-middleware'; | ||
export { preload } from './utils/preload'; | ||
export * from './types'; |
@@ -7,2 +7,3 @@ import * as revalidateEvents from './constants'; | ||
Record<string, [any, number]>, | ||
Record<string, FetcherResponse<any>>, | ||
ScopedMutator, | ||
@@ -9,0 +10,0 @@ (key: string, value: any, prev: any) => void, |
import { FC, PropsWithChildren } from 'react'; | ||
import { SWRConfiguration, FullConfiguration, ProviderConfiguration, Cache } from '../types'; | ||
declare type Config = SWRConfiguration & Partial<ProviderConfiguration> & { | ||
provider?: (cache: Readonly<Cache>) => Cache; | ||
}; | ||
export declare const SWRConfigContext: import("react").Context<Partial<FullConfiguration<Cache<any>>>>; | ||
declare const SWRConfig: FC<PropsWithChildren<{ | ||
value?: SWRConfiguration & Partial<ProviderConfiguration> & { | ||
provider?: (cache: Readonly<Cache>) => Cache; | ||
}; | ||
value?: Config | ((parentConfig?: Config) => Config); | ||
}>>; | ||
export default SWRConfig; |
@@ -33,6 +33,6 @@ import React, { useEffect, useLayoutEffect, createContext, useContext, useState, createElement, useRef, useCallback } from 'react'; | ||
var prev = cache.get(key); | ||
state[4](key, mergeObjects(prev, info), prev || EMPTY_CACHE); | ||
state[5](key, mergeObjects(prev, info), prev || EMPTY_CACHE); | ||
}, | ||
// Subscriber | ||
state[5] | ||
state[6] | ||
]; | ||
@@ -185,3 +185,3 @@ }; | ||
/*! ***************************************************************************** | ||
/****************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
@@ -294,5 +294,5 @@ | ||
return __awaiter(void 0, void 0, void 0, function () { | ||
var cache, _key, _data, _opts, options, populateCache, optimisticData, revalidate, rollbackOnError, key, _a, get, set, _b, EVENT_REVALIDATORS, MUTATION, FETCH, revalidators, startRevalidate, data, error, beforeMutationTs, hasOptimisticData, state, currentData, originalData, res; | ||
return __generator(this, function (_c) { | ||
switch (_c.label) { | ||
var cache, _key, _data, _opts, options, populateCache, optimisticData, revalidate, rollbackOnError, key, _a, get, set, _b, EVENT_REVALIDATORS, MUTATION, FETCH, revalidators, startRevalidate, data, error, beforeMutationTs, hasOptimisticData, state, displayedData, committedData, res; | ||
return __generator(this, function (_d) { | ||
switch (_d.label) { | ||
case 0: | ||
@@ -334,10 +334,11 @@ cache = args[0], _key = args[1], _data = args[2], _opts = args[3]; | ||
state = get(); | ||
currentData = state.data; | ||
originalData = isUndefined(state._o) ? currentData : state._o; | ||
displayedData = state.data; | ||
committedData = isUndefined(state._c) ? displayedData : state._c; | ||
// Do optimistic data update. | ||
if (hasOptimisticData) { | ||
optimisticData = isFunction(optimisticData) | ||
? optimisticData(originalData) | ||
? optimisticData(committedData) | ||
: optimisticData; | ||
set({ data: optimisticData, _o: originalData }); | ||
// When we set optimistic data, backup the current committedData data in `_c`. | ||
set({ data: optimisticData, _c: committedData }); | ||
} | ||
@@ -347,3 +348,3 @@ if (isFunction(data)) { | ||
try { | ||
data = data(originalData); | ||
data = data(committedData); | ||
} | ||
@@ -366,3 +367,3 @@ catch (err) { | ||
// avoid race conditions. | ||
data = _c.sent(); | ||
data = _d.sent(); | ||
// Check if other mutations have occurred since we've started this mutation. | ||
@@ -380,6 +381,7 @@ // If there's a race we don't update cache or broadcast the change, | ||
populateCache = true; | ||
data = originalData; | ||
set({ data: originalData }); | ||
data = committedData; | ||
// Reset data to be the latest committed data, and clear the `_c` value. | ||
set({ data: data, _c: UNDEFINED }); | ||
} | ||
_c.label = 2; | ||
_d.label = 2; | ||
case 2: | ||
@@ -391,9 +393,9 @@ // If we should write back the cache after request. | ||
if (isFunction(populateCache)) { | ||
data = populateCache(data, originalData); | ||
data = populateCache(data, committedData); | ||
} | ||
// Only update cached data if there's no error. Data can be `undefined` here. | ||
set({ data: data }); | ||
set({ data: data, _c: UNDEFINED }); | ||
} | ||
// Always update or reset the error and original data field. | ||
set({ error: error, _o: UNDEFINED }); | ||
// Always update error and original data here. | ||
set({ error: error }); | ||
} | ||
@@ -403,6 +405,10 @@ // Reset the timestamp to mark the mutation has ended. | ||
return [4 /*yield*/, startRevalidate() | ||
// Throw error or return data | ||
// The mutation and revalidation are ended, we can clear it since the data is | ||
// not an optimistic value anymore. | ||
]; | ||
case 3: | ||
res = _c.sent(); | ||
res = _d.sent(); | ||
// The mutation and revalidation are ended, we can clear it since the data is | ||
// not an optimistic value anymore. | ||
set({ _c: UNDEFINED }); | ||
// Throw error or return data | ||
@@ -461,2 +467,3 @@ if (error) | ||
{}, | ||
{}, | ||
mutate_1, | ||
@@ -494,3 +501,3 @@ setter_1, | ||
} | ||
return [provider, SWRGlobalState.get(provider)[3]]; | ||
return [provider, SWRGlobalState.get(provider)[4]]; | ||
}; | ||
@@ -563,10 +570,15 @@ | ||
var value = props.value; | ||
var parentConfig = useContext(SWRConfigContext); | ||
var isFunctionalConfig = isFunction(value); | ||
var config = isFunctionalConfig ? value(parentConfig) : value; | ||
// Extend parent context values and middleware. | ||
var extendedConfig = mergeConfigs(useContext(SWRConfigContext), value); | ||
var extendedConfig = isFunctionalConfig | ||
? config | ||
: mergeConfigs(parentConfig, config); | ||
// Should not use the inherited provider. | ||
var provider = value && value.provider; | ||
var provider = config && config.provider; | ||
// Use a lazy initialized state to create the cache on first access. | ||
var cacheContext = useState(function () { | ||
return provider | ||
? initCache(provider(extendedConfig.cache || cache), value) | ||
? initCache(provider(extendedConfig.cache || cache), config) | ||
: UNDEFINED; | ||
@@ -601,2 +613,31 @@ })[0]; | ||
var preload = function (key_, fetcher) { | ||
var req = fetcher(key_); | ||
var key = serialize(key_)[0]; | ||
var _a = SWRGlobalState.get(cache), PRELOAD = _a[3]; | ||
PRELOAD[key] = req; | ||
return req; | ||
}; | ||
var middleware = function (useSWRNext) { return function (key_, fetcher_, config) { | ||
// fetcher might be a sync function, so this should not be an async function | ||
var fetcher = fetcher_ && | ||
(function () { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
var key = serialize(key_)[0]; | ||
var _a = SWRGlobalState.get(cache), PRELOAD = _a[3]; | ||
var req = PRELOAD[key]; | ||
if (req) { | ||
delete PRELOAD[key]; | ||
return req; | ||
} | ||
return fetcher_.apply(void 0, args); | ||
}); | ||
return useSWRNext(key_, fetcher, config); | ||
}; }; | ||
var BUILT_IN_MIDDLEWARE = [middleware]; | ||
// It's tricky to pass generic types as parameters, so we just directly override | ||
@@ -619,6 +660,5 @@ // the types here. | ||
var use = config.use; | ||
if (use) { | ||
for (var i = use.length; i--;) { | ||
next = use[i](next); | ||
} | ||
var middleware = (use || []).concat(BUILT_IN_MIDDLEWARE); | ||
for (var i = middleware.length; i--;) { | ||
next = middleware[i](next); | ||
} | ||
@@ -727,2 +767,2 @@ return next(key, fn || config.fetcher, config); | ||
export { IS_REACT_LEGACY, IS_SERVER, OBJECT, SWRConfig, SWRGlobalState, UNDEFINED, cache, compare, createCacheHelper, defaultConfig, defaultConfigOptions, getTimestamp, hasRequestAnimationFrame, initCache, internalMutate, isDocumentDefined, isEmptyCache, isFunction, isUndefined, isWindowDefined, mergeConfigs, mergeObjects, mutate, noop, normalize, preset, rAF, constants as revalidateEvents, serialize, slowConnection, stableHash, subscribeCallback, useIsomorphicLayoutEffect, useSWRConfig, useStateWithDeps, withArgs, withMiddleware }; | ||
export { IS_REACT_LEGACY, IS_SERVER, OBJECT, SWRConfig, SWRGlobalState, UNDEFINED, cache, compare, createCacheHelper, defaultConfig, defaultConfigOptions, getTimestamp, hasRequestAnimationFrame, initCache, internalMutate, isDocumentDefined, isEmptyCache, isFunction, isUndefined, isWindowDefined, mergeConfigs, mergeObjects, mutate, noop, normalize, preload, preset, rAF, constants as revalidateEvents, serialize, slowConnection, stableHash, subscribeCallback, useIsomorphicLayoutEffect, useSWRConfig, useStateWithDeps, withArgs, withMiddleware }; |
@@ -39,6 +39,6 @@ Object.defineProperty(exports, '__esModule', { value: true }); | ||
var prev = cache.get(key); | ||
state[4](key, mergeObjects(prev, info), prev || EMPTY_CACHE); | ||
state[5](key, mergeObjects(prev, info), prev || EMPTY_CACHE); | ||
}, | ||
// Subscriber | ||
state[5] | ||
state[6] | ||
]; | ||
@@ -170,3 +170,3 @@ }; | ||
var IS_REACT_LEGACY = !React__default['default'].useId; | ||
var IS_REACT_LEGACY = !React__default["default"].useId; | ||
var IS_SERVER = !isWindowDefined || 'Deno' in window; | ||
@@ -192,3 +192,3 @@ // Polyfill requestAnimationFrame | ||
/*! ***************************************************************************** | ||
/****************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
@@ -301,5 +301,5 @@ | ||
return __awaiter(void 0, void 0, void 0, function () { | ||
var cache, _key, _data, _opts, options, populateCache, optimisticData, revalidate, rollbackOnError, key, _a, get, set, _b, EVENT_REVALIDATORS, MUTATION, FETCH, revalidators, startRevalidate, data, error, beforeMutationTs, hasOptimisticData, state, currentData, originalData, res; | ||
return __generator(this, function (_c) { | ||
switch (_c.label) { | ||
var cache, _key, _data, _opts, options, populateCache, optimisticData, revalidate, rollbackOnError, key, _a, get, set, _b, EVENT_REVALIDATORS, MUTATION, FETCH, revalidators, startRevalidate, data, error, beforeMutationTs, hasOptimisticData, state, displayedData, committedData, res; | ||
return __generator(this, function (_d) { | ||
switch (_d.label) { | ||
case 0: | ||
@@ -341,10 +341,11 @@ cache = args[0], _key = args[1], _data = args[2], _opts = args[3]; | ||
state = get(); | ||
currentData = state.data; | ||
originalData = isUndefined(state._o) ? currentData : state._o; | ||
displayedData = state.data; | ||
committedData = isUndefined(state._c) ? displayedData : state._c; | ||
// Do optimistic data update. | ||
if (hasOptimisticData) { | ||
optimisticData = isFunction(optimisticData) | ||
? optimisticData(originalData) | ||
? optimisticData(committedData) | ||
: optimisticData; | ||
set({ data: optimisticData, _o: originalData }); | ||
// When we set optimistic data, backup the current committedData data in `_c`. | ||
set({ data: optimisticData, _c: committedData }); | ||
} | ||
@@ -354,3 +355,3 @@ if (isFunction(data)) { | ||
try { | ||
data = data(originalData); | ||
data = data(committedData); | ||
} | ||
@@ -373,3 +374,3 @@ catch (err) { | ||
// avoid race conditions. | ||
data = _c.sent(); | ||
data = _d.sent(); | ||
// Check if other mutations have occurred since we've started this mutation. | ||
@@ -387,6 +388,7 @@ // If there's a race we don't update cache or broadcast the change, | ||
populateCache = true; | ||
data = originalData; | ||
set({ data: originalData }); | ||
data = committedData; | ||
// Reset data to be the latest committed data, and clear the `_c` value. | ||
set({ data: data, _c: UNDEFINED }); | ||
} | ||
_c.label = 2; | ||
_d.label = 2; | ||
case 2: | ||
@@ -398,9 +400,9 @@ // If we should write back the cache after request. | ||
if (isFunction(populateCache)) { | ||
data = populateCache(data, originalData); | ||
data = populateCache(data, committedData); | ||
} | ||
// Only update cached data if there's no error. Data can be `undefined` here. | ||
set({ data: data }); | ||
set({ data: data, _c: UNDEFINED }); | ||
} | ||
// Always update or reset the error and original data field. | ||
set({ error: error, _o: UNDEFINED }); | ||
// Always update error and original data here. | ||
set({ error: error }); | ||
} | ||
@@ -410,6 +412,10 @@ // Reset the timestamp to mark the mutation has ended. | ||
return [4 /*yield*/, startRevalidate() | ||
// Throw error or return data | ||
// The mutation and revalidation are ended, we can clear it since the data is | ||
// not an optimistic value anymore. | ||
]; | ||
case 3: | ||
res = _c.sent(); | ||
res = _d.sent(); | ||
// The mutation and revalidation are ended, we can clear it since the data is | ||
// not an optimistic value anymore. | ||
set({ _c: UNDEFINED }); | ||
// Throw error or return data | ||
@@ -468,2 +474,3 @@ if (error) | ||
{}, | ||
{}, | ||
mutate_1, | ||
@@ -501,3 +508,3 @@ setter_1, | ||
} | ||
return [provider, SWRGlobalState.get(provider)[3]]; | ||
return [provider, SWRGlobalState.get(provider)[4]]; | ||
}; | ||
@@ -570,10 +577,15 @@ | ||
var value = props.value; | ||
var parentConfig = React.useContext(SWRConfigContext); | ||
var isFunctionalConfig = isFunction(value); | ||
var config = isFunctionalConfig ? value(parentConfig) : value; | ||
// Extend parent context values and middleware. | ||
var extendedConfig = mergeConfigs(React.useContext(SWRConfigContext), value); | ||
var extendedConfig = isFunctionalConfig | ||
? config | ||
: mergeConfigs(parentConfig, config); | ||
// Should not use the inherited provider. | ||
var provider = value && value.provider; | ||
var provider = config && config.provider; | ||
// Use a lazy initialized state to create the cache on first access. | ||
var cacheContext = React.useState(function () { | ||
return provider | ||
? initCache(provider(extendedConfig.cache || cache), value) | ||
? initCache(provider(extendedConfig.cache || cache), config) | ||
: UNDEFINED; | ||
@@ -608,2 +620,31 @@ })[0]; | ||
var preload = function (key_, fetcher) { | ||
var req = fetcher(key_); | ||
var key = serialize(key_)[0]; | ||
var _a = SWRGlobalState.get(cache), PRELOAD = _a[3]; | ||
PRELOAD[key] = req; | ||
return req; | ||
}; | ||
var middleware = function (useSWRNext) { return function (key_, fetcher_, config) { | ||
// fetcher might be a sync function, so this should not be an async function | ||
var fetcher = fetcher_ && | ||
(function () { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
var key = serialize(key_)[0]; | ||
var _a = SWRGlobalState.get(cache), PRELOAD = _a[3]; | ||
var req = PRELOAD[key]; | ||
if (req) { | ||
delete PRELOAD[key]; | ||
return req; | ||
} | ||
return fetcher_.apply(void 0, args); | ||
}); | ||
return useSWRNext(key_, fetcher, config); | ||
}; }; | ||
var BUILT_IN_MIDDLEWARE = [middleware]; | ||
// It's tricky to pass generic types as parameters, so we just directly override | ||
@@ -626,6 +667,5 @@ // the types here. | ||
var use = config.use; | ||
if (use) { | ||
for (var i = use.length; i--;) { | ||
next = use[i](next); | ||
} | ||
var middleware = (use || []).concat(BUILT_IN_MIDDLEWARE); | ||
for (var i = middleware.length; i--;) { | ||
next = middleware[i](next); | ||
} | ||
@@ -690,3 +730,3 @@ return next(key, fn || config.fetcher, config); | ||
else { | ||
React__default['default'].startTransition(function () { return rerender({}); }); | ||
React__default["default"].startTransition(function () { return rerender({}); }); | ||
} | ||
@@ -760,2 +800,3 @@ } | ||
exports.normalize = normalize; | ||
exports.preload = preload; | ||
exports.preset = preset; | ||
@@ -762,0 +803,0 @@ exports.rAF = rAF; |
@@ -8,2 +8,9 @@ { | ||
"exports": "./dist/index.mjs", | ||
"private": true, | ||
"scripts": { | ||
"watch": "bunchee index.ts --no-sourcemap -w", | ||
"build": "bunchee index.ts --no-sourcemap", | ||
"types:check": "tsc --noEmit", | ||
"clean": "rimraf dist" | ||
}, | ||
"peerDependencies": { | ||
@@ -10,0 +17,0 @@ "react": "*" |
@@ -6,2 +6,3 @@ import useSWR from './use-swr'; | ||
export { mutate } from 'swr/_internal'; | ||
export { preload } from 'swr/_internal'; | ||
export type { SWRConfiguration, Revalidator, RevalidatorOptions, Key, KeyLoader, KeyedMutator, SWRHook, SWRResponse, Cache, BareFetcher, Fetcher, MutatorCallback, MutatorOptions, Middleware, Arguments, State } from 'swr/_internal'; |
/// <reference types="react" /> | ||
import { defaultConfig, Fetcher, Key, SWRResponse, FullConfiguration, SWRConfiguration, SWRHook } from 'swr/_internal'; | ||
export declare const useSWRHandler: <Data = any, Error_1 = any>(_key: Key, fetcher: ((args: string) => import("swr/_internal").FetcherResponse<Data>) | ((args: [any, ...unknown[]]) => import("swr/_internal").FetcherResponse<Data>) | ((args: readonly [any, ...unknown[]]) => import("swr/_internal").FetcherResponse<Data>) | ((args: Record<any, any>) => import("swr/_internal").FetcherResponse<Data>) | ((args: string | [any, ...unknown[]] | readonly [any, ...unknown[]] | Record<any, any>) => import("swr/_internal").FetcherResponse<Data>) | null, config: import("swr/_internal").InternalConfiguration<import("swr/_internal").Cache<any>> & import("swr/_internal").PublicConfiguration<any, any, import("swr/_internal").BareFetcher<unknown>> & Partial<import("swr/_internal").PublicConfiguration<Data, Error_1, import("swr/_internal").BareFetcher<any>>>) => SWRResponse<Data, Error_1>; | ||
export declare const useSWRHandler: <Data = any, Error_1 = any>(_key: Key, fetcher: ((args: string) => import("_internal/types").FetcherResponse<Data>) | ((args: [any, ...unknown[]]) => import("_internal/types").FetcherResponse<Data>) | ((args: readonly [any, ...unknown[]]) => import("_internal/types").FetcherResponse<Data>) | ((args: Record<any, any>) => import("_internal/types").FetcherResponse<Data>) | ((args: string | [any, ...unknown[]] | readonly [any, ...unknown[]] | Record<any, any>) => import("_internal/types").FetcherResponse<Data>) | null, config: import("_internal/types").InternalConfiguration<import("_internal/types").Cache<any>> & import("_internal/types").PublicConfiguration<any, any, import("_internal/types").BareFetcher<unknown>> & Partial<import("_internal/types").PublicConfiguration<Data, Error_1, import("_internal/types").BareFetcher<any>>>) => SWRResponse<Data, Error_1>; | ||
export declare const SWRConfig: import("react").FC<import("react").PropsWithChildren<{ | ||
value?: (Partial<import("swr/_internal").PublicConfiguration<any, any, import("swr/_internal").BareFetcher<any>>> & Partial<import("swr/_internal").ProviderConfiguration> & { | ||
provider?: ((cache: Readonly<import("swr/_internal").Cache<any>>) => import("swr/_internal").Cache<any>) | undefined; | ||
value?: (Partial<import("_internal/types").PublicConfiguration<any, any, import("_internal/types").BareFetcher<any>>> & Partial<import("_internal/types").ProviderConfiguration> & { | ||
provider?: ((cache: Readonly<import("_internal/types").Cache<any>>) => import("_internal/types").Cache<any>) | undefined; | ||
}) | ((parentConfig?: (Partial<import("_internal/types").PublicConfiguration<any, any, import("_internal/types").BareFetcher<any>>> & Partial<import("_internal/types").ProviderConfiguration> & { | ||
provider?: ((cache: Readonly<import("_internal/types").Cache<any>>) => import("_internal/types").Cache<any>) | undefined; | ||
}) | undefined) => Partial<import("_internal/types").PublicConfiguration<any, any, import("_internal/types").BareFetcher<any>>> & Partial<import("_internal/types").ProviderConfiguration> & { | ||
provider?: ((cache: Readonly<import("_internal/types").Cache<any>>) => import("_internal/types").Cache<any>) | undefined; | ||
}) | undefined; | ||
}>> & { | ||
default: FullConfiguration; | ||
defaultValue: FullConfiguration; | ||
}; | ||
@@ -11,0 +15,0 @@ export declare const unstable_serialize: (key: Key) => string; |
import { useRef, useCallback, useDebugValue } from 'react'; | ||
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector.js'; | ||
import { OBJECT, SWRConfig as SWRConfig$1, defaultConfig, withArgs, SWRGlobalState, serialize, createCacheHelper, isUndefined, internalMutate, UNDEFINED, useIsomorphicLayoutEffect, subscribeCallback, IS_SERVER, rAF, IS_REACT_LEGACY, isEmptyCache, revalidateEvents, isFunction, getTimestamp } from 'swr/_internal'; | ||
export { mutate, useSWRConfig } from 'swr/_internal'; | ||
export { mutate, preload, useSWRConfig } from 'swr/_internal'; | ||
/*! ***************************************************************************** | ||
/****************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
@@ -134,4 +134,3 @@ | ||
var cached = useSyncExternalStoreWithSelector(useCallback(function (callback) { | ||
return subscribeCache(key, function (current) { | ||
stateRef.current = current; | ||
return subscribeCache(key, function () { | ||
callback(); | ||
@@ -142,3 +141,2 @@ }); | ||
[cache, key]), getSnapshot, getSnapshot, selector, isEqual); | ||
var stateRef = useRef(cached); | ||
var isInitialMount = !initialMountedRef.current; | ||
@@ -182,12 +180,6 @@ var cachedData = cached.data; | ||
var isLoading = cached.isLoading || defaultValidatingState; | ||
var currentState = { | ||
data: data, | ||
error: error, | ||
isValidating: isValidating, | ||
isLoading: isLoading | ||
}; | ||
// The revalidation function is a carefully crafted wrapper of the original | ||
// `fetcher`, to correctly handle the many edge cases. | ||
var revalidate = useCallback(function (revalidateOpts) { return __awaiter(void 0, void 0, void 0, function () { | ||
var currentFetcher, newData, startAt, loading, opts, shouldStartNewRequest, callbackSafeguard, finalState, finishRequestAndUpdateState, cleanupState, initialState, mutationInfo, err_1, currentConfig, shouldRetryOnError; | ||
var currentFetcher, newData, startAt, loading, opts, shouldStartNewRequest, callbackSafeguard, finalState, finishRequestAndUpdateState, cleanupState, initialState, mutationInfo, cacheData, err_1, currentConfig, shouldRetryOnError; | ||
var _a; | ||
@@ -235,3 +227,2 @@ return __generator(this, function (_b) { | ||
} | ||
setCache(initialState); | ||
_b.label = 1; | ||
@@ -241,2 +232,3 @@ case 1: | ||
if (shouldStartNewRequest) { | ||
setCache(initialState); | ||
// If no cache being rendered currently (it shows a blank page), | ||
@@ -299,14 +291,6 @@ // we trigger the loading slow event. | ||
} | ||
// Deep compare with latest state to avoid extra re-renders. | ||
// For local state, compare and assign. | ||
if (!compare(stateRef.current.data, newData)) { | ||
finalState.data = newData; | ||
} | ||
else { | ||
// `data` and `newData` are deeply equal (serialized value). | ||
// So it should be safe to broadcast the stale data to keep referential equality (===). | ||
finalState.data = stateRef.current.data; | ||
// At the end of this function, `broadcastState` invokes the `onStateUpdate` function, | ||
// which takes care of avoiding the re-render. | ||
} | ||
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. | ||
@@ -383,3 +367,2 @@ if (shouldStartNewRequest) { | ||
configRef.current = config; | ||
stateRef.current = currentState; | ||
// Handle laggy data updates. If there's cached data of the current key, | ||
@@ -461,3 +444,3 @@ // it'll be the correct reference. | ||
// Only revalidate when the page is visible, online and not errored. | ||
if (!stateRef.current.error && | ||
if (!getCache().error && | ||
(refreshWhenHidden || getConfig().isVisible()) && | ||
@@ -519,3 +502,3 @@ (refreshWhenOffline || getConfig().isOnline())) { | ||
}; | ||
var SWRConfig = OBJECT.defineProperty(SWRConfig$1, 'default', { | ||
var SWRConfig = OBJECT.defineProperty(SWRConfig$1, 'defaultValue', { | ||
value: defaultConfig | ||
@@ -522,0 +505,0 @@ }); |
@@ -7,3 +7,3 @@ Object.defineProperty(exports, '__esModule', { value: true }); | ||
/*! ***************************************************************************** | ||
/****************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
@@ -136,4 +136,3 @@ | ||
var cached = withSelector_js.useSyncExternalStoreWithSelector(react.useCallback(function (callback) { | ||
return subscribeCache(key, function (current) { | ||
stateRef.current = current; | ||
return subscribeCache(key, function () { | ||
callback(); | ||
@@ -144,3 +143,2 @@ }); | ||
[cache, key]), getSnapshot, getSnapshot, selector, isEqual); | ||
var stateRef = react.useRef(cached); | ||
var isInitialMount = !initialMountedRef.current; | ||
@@ -184,12 +182,6 @@ var cachedData = cached.data; | ||
var isLoading = cached.isLoading || defaultValidatingState; | ||
var currentState = { | ||
data: data, | ||
error: error, | ||
isValidating: isValidating, | ||
isLoading: isLoading | ||
}; | ||
// The revalidation function is a carefully crafted wrapper of the original | ||
// `fetcher`, to correctly handle the many edge cases. | ||
var revalidate = react.useCallback(function (revalidateOpts) { return __awaiter(void 0, void 0, void 0, function () { | ||
var currentFetcher, newData, startAt, loading, opts, shouldStartNewRequest, callbackSafeguard, finalState, finishRequestAndUpdateState, cleanupState, initialState, mutationInfo, err_1, currentConfig, shouldRetryOnError; | ||
var currentFetcher, newData, startAt, loading, opts, shouldStartNewRequest, callbackSafeguard, finalState, finishRequestAndUpdateState, cleanupState, initialState, mutationInfo, cacheData, err_1, currentConfig, shouldRetryOnError; | ||
var _a; | ||
@@ -237,3 +229,2 @@ return __generator(this, function (_b) { | ||
} | ||
setCache(initialState); | ||
_b.label = 1; | ||
@@ -243,2 +234,3 @@ case 1: | ||
if (shouldStartNewRequest) { | ||
setCache(initialState); | ||
// If no cache being rendered currently (it shows a blank page), | ||
@@ -301,14 +293,6 @@ // we trigger the loading slow event. | ||
} | ||
// Deep compare with latest state to avoid extra re-renders. | ||
// For local state, compare and assign. | ||
if (!compare(stateRef.current.data, newData)) { | ||
finalState.data = newData; | ||
} | ||
else { | ||
// `data` and `newData` are deeply equal (serialized value). | ||
// So it should be safe to broadcast the stale data to keep referential equality (===). | ||
finalState.data = stateRef.current.data; | ||
// At the end of this function, `broadcastState` invokes the `onStateUpdate` function, | ||
// which takes care of avoiding the re-render. | ||
} | ||
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. | ||
@@ -385,3 +369,2 @@ if (shouldStartNewRequest) { | ||
configRef.current = config; | ||
stateRef.current = currentState; | ||
// Handle laggy data updates. If there's cached data of the current key, | ||
@@ -463,3 +446,3 @@ // it'll be the correct reference. | ||
// Only revalidate when the page is visible, online and not errored. | ||
if (!stateRef.current.error && | ||
if (!getCache().error && | ||
(refreshWhenHidden || getConfig().isVisible()) && | ||
@@ -521,3 +504,3 @@ (refreshWhenOffline || getConfig().isOnline())) { | ||
}; | ||
var SWRConfig = _internal.OBJECT.defineProperty(_internal.SWRConfig, 'default', { | ||
var SWRConfig = _internal.OBJECT.defineProperty(_internal.SWRConfig, 'defaultValue', { | ||
value: _internal.defaultConfig | ||
@@ -532,14 +515,14 @@ }); | ||
enumerable: true, | ||
get: function () { | ||
return _internal.mutate; | ||
} | ||
get: function () { return _internal.mutate; } | ||
}); | ||
Object.defineProperty(exports, 'preload', { | ||
enumerable: true, | ||
get: function () { return _internal.preload; } | ||
}); | ||
Object.defineProperty(exports, 'useSWRConfig', { | ||
enumerable: true, | ||
get: function () { | ||
return _internal.useSWRConfig; | ||
} | ||
get: function () { return _internal.useSWRConfig; } | ||
}); | ||
exports.SWRConfig = SWRConfig; | ||
exports['default'] = useSWR; | ||
exports["default"] = useSWR; | ||
exports.unstable_serialize = unstable_serialize; |
@@ -17,5 +17,5 @@ Object.defineProperty(exports, '__esModule', { value: true }); | ||
}; }; | ||
var index = _internal.withMiddleware(useSWR__default['default'], immutable); | ||
var index = _internal.withMiddleware(useSWR__default["default"], immutable); | ||
exports['default'] = index; | ||
exports["default"] = index; | ||
exports.immutable = immutable; |
@@ -8,2 +8,9 @@ { | ||
"exports": "./dist/index.mjs", | ||
"private": true, | ||
"scripts": { | ||
"watch": "bunchee index.ts --no-sourcemap -w", | ||
"build": "bunchee index.ts --no-sourcemap", | ||
"types:check": "tsc --noEmit", | ||
"clean": "rimraf dist" | ||
}, | ||
"peerDependencies": { | ||
@@ -10,0 +17,0 @@ "swr": "*", |
import { useRef, useCallback } from 'react'; | ||
import useSWR from 'swr'; | ||
import { withMiddleware, serialize, createCacheHelper, isUndefined, useIsomorphicLayoutEffect, isFunction, UNDEFINED } from 'swr/_internal'; | ||
import { withMiddleware, serialize, createCacheHelper, isUndefined, useIsomorphicLayoutEffect, isFunction, UNDEFINED, mergeObjects } from 'swr/_internal'; | ||
import { useSyncExternalStore } from 'use-sync-external-store/shim/index.js'; | ||
/*! ***************************************************************************** | ||
/****************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
@@ -21,13 +21,2 @@ | ||
var __assign = function() { | ||
__assign = Object.assign || function __assign(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
@@ -136,3 +125,3 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
var swr = useSWRNext(infiniteKey, function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var _a, forceRevalidateAll, originalData, data, pageSize, previousPageData, i, _b, pageKey, pageArg, _c, getSWRCacahe, setSWRCache, pageData, shouldFetchPage; | ||
var _a, forceRevalidateAll, originalData, data, pageSize, previousPageData, i, _b, pageKey, pageArg, _c, getSWRCache, setSWRCache, pageData, shouldFetchPage; | ||
return __generator(this, function (_d) { | ||
@@ -154,4 +143,4 @@ switch (_d.label) { | ||
} | ||
_c = createCacheHelper(cache, pageKey), getSWRCacahe = _c[0], setSWRCache = _c[1]; | ||
pageData = getSWRCacahe().data; | ||
_c = createCacheHelper(cache, pageKey), getSWRCache = _c[0], setSWRCache = _c[1]; | ||
pageData = getSWRCache().data; | ||
shouldFetchPage = revalidateAll || | ||
@@ -169,3 +158,3 @@ forceRevalidateAll || | ||
pageData = _d.sent(); | ||
setSWRCache(__assign(__assign({}, getSWRCacahe()), { data: pageData })); | ||
setSWRCache(mergeObjects(getSWRCache(), { data: pageData })); | ||
_d.label = 3; | ||
@@ -172,0 +161,0 @@ case 3: |
@@ -12,3 +12,3 @@ Object.defineProperty(exports, '__esModule', { value: true }); | ||
/*! ***************************************************************************** | ||
/****************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
@@ -28,13 +28,2 @@ | ||
var __assign = function() { | ||
__assign = Object.assign || function __assign(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
@@ -143,3 +132,3 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
var swr = useSWRNext(infiniteKey, function () { return __awaiter(void 0, void 0, void 0, function () { | ||
var _a, forceRevalidateAll, originalData, data, pageSize, previousPageData, i, _b, pageKey, pageArg, _c, getSWRCacahe, setSWRCache, pageData, shouldFetchPage; | ||
var _a, forceRevalidateAll, originalData, data, pageSize, previousPageData, i, _b, pageKey, pageArg, _c, getSWRCache, setSWRCache, pageData, shouldFetchPage; | ||
return __generator(this, function (_d) { | ||
@@ -161,4 +150,4 @@ switch (_d.label) { | ||
} | ||
_c = _internal.createCacheHelper(cache, pageKey), getSWRCacahe = _c[0], setSWRCache = _c[1]; | ||
pageData = getSWRCacahe().data; | ||
_c = _internal.createCacheHelper(cache, pageKey), getSWRCache = _c[0], setSWRCache = _c[1]; | ||
pageData = getSWRCache().data; | ||
shouldFetchPage = revalidateAll || | ||
@@ -176,3 +165,3 @@ forceRevalidateAll || | ||
pageData = _d.sent(); | ||
setSWRCache(__assign(__assign({}, getSWRCacahe()), { data: pageData })); | ||
setSWRCache(_internal.mergeObjects(getSWRCache(), { data: pageData })); | ||
_d.label = 3; | ||
@@ -288,6 +277,6 @@ case 3: | ||
}); | ||
var index = _internal.withMiddleware(useSWR__default['default'], infinite); | ||
var index = _internal.withMiddleware(useSWR__default["default"], infinite); | ||
exports['default'] = index; | ||
exports["default"] = index; | ||
exports.infinite = infinite; | ||
exports.unstable_serialize = unstable_serialize; |
@@ -8,2 +8,9 @@ { | ||
"exports": "./dist/index.mjs", | ||
"private": true, | ||
"scripts": { | ||
"watch": "bunchee index.ts --no-sourcemap -w", | ||
"build": "bunchee index.ts --no-sourcemap", | ||
"types:check": "tsc --noEmit", | ||
"clean": "rimraf dist" | ||
}, | ||
"peerDependencies": { | ||
@@ -10,0 +17,0 @@ "swr": "*", |
@@ -5,3 +5,3 @@ import { useRef, useCallback } from 'react'; | ||
/*! ***************************************************************************** | ||
/****************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
@@ -92,3 +92,5 @@ | ||
_d.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, mutate(serializedKey, fetcher(resolvedKey, { arg: arg }), options) | ||
return [4 /*yield*/, mutate(serializedKey, | ||
// FIXME: Error shouldn't be broadcasted here. | ||
fetcher(resolvedKey, { arg: arg }), options) | ||
// If it's reset after the mutation, we don't broadcast any state change. | ||
@@ -100,3 +102,3 @@ ]; | ||
if (ditchMutationsUntilRef.current <= mutationStartedAt) { | ||
setState({ data: data, isMutating: false }); | ||
setState({ data: data, isMutating: false, error: undefined }); | ||
(_b = options.onSuccess) === null || _b === void 0 ? void 0 : _b.call(options, data, serializedKey, options); | ||
@@ -103,0 +105,0 @@ } |
@@ -11,3 +11,3 @@ Object.defineProperty(exports, '__esModule', { value: true }); | ||
/*! ***************************************************************************** | ||
/****************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
@@ -98,3 +98,5 @@ | ||
_d.trys.push([1, 3, , 4]); | ||
return [4 /*yield*/, mutate(serializedKey, fetcher(resolvedKey, { arg: arg }), options) | ||
return [4 /*yield*/, mutate(serializedKey, | ||
// FIXME: Error shouldn't be broadcasted here. | ||
fetcher(resolvedKey, { arg: arg }), options) | ||
// If it's reset after the mutation, we don't broadcast any state change. | ||
@@ -106,3 +108,3 @@ ]; | ||
if (ditchMutationsUntilRef.current <= mutationStartedAt) { | ||
setState({ data: data, isMutating: false }); | ||
setState({ data: data, isMutating: false, error: undefined }); | ||
(_b = options.onSuccess) === null || _b === void 0 ? void 0 : _b.call(options, data, serializedKey, options); | ||
@@ -155,4 +157,4 @@ } | ||
}); | ||
var index = _internal.withMiddleware(useSWR__default['default'], mutation); | ||
var index = _internal.withMiddleware(useSWR__default["default"], mutation); | ||
exports['default'] = index; | ||
exports["default"] = index; |
@@ -8,2 +8,9 @@ { | ||
"exports": "./dist/index.mjs", | ||
"private": true, | ||
"scripts": { | ||
"watch": "bunchee index.ts --no-sourcemap -w", | ||
"build": "bunchee index.ts --no-sourcemap", | ||
"types:check": "tsc --noEmit", | ||
"clean": "rimraf dist" | ||
}, | ||
"peerDependencies": { | ||
@@ -10,0 +17,0 @@ "swr": "*", |
{ | ||
"name": "swr", | ||
"version": "2.0.0-beta.3", | ||
"version": "2.0.0-beta.4", | ||
"description": "React Hooks library for remote data fetching", | ||
@@ -13,2 +13,3 @@ "keywords": [ | ||
], | ||
"packageManager": "pnpm@7.1.0", | ||
"main": "./core/dist/index.js", | ||
@@ -56,3 +57,3 @@ "module": "./core/dist/index.esm.js", | ||
"_internal/dist/**", | ||
"core/dist/package.json", | ||
"core/package.json", | ||
"infinite/package.json", | ||
@@ -68,20 +69,23 @@ "immutable/package.json", | ||
"scripts": { | ||
"clean": "rimraf core/dist infinite/dist immutable/dist mutation/dist", | ||
"build": "yarn build:internal && yarn build:core && yarn build:infinite && yarn build:immutable && yarn build:mutation", | ||
"watch": "npm-run-all -p watch:core watch:infinite watch:immutable watch:mutation", | ||
"watch:core": "yarn build:core -w", | ||
"watch:infinite": "yarn build:infinite -w", | ||
"watch:immutable": "yarn build:immutable -w", | ||
"watch:mutation": "yarn build:mutation -w", | ||
"build:core": "bunchee index.ts --cwd core --no-sourcemap", | ||
"build:infinite": "bunchee index.ts --cwd infinite --no-sourcemap", | ||
"build:immutable": "bunchee index.ts --cwd immutable --no-sourcemap", | ||
"build:mutation": "bunchee index.ts --cwd mutation --no-sourcemap", | ||
"build:internal": "bunchee index.ts --cwd _internal --no-sourcemap", | ||
"prepublishOnly": "yarn clean && yarn build", | ||
"publish-beta": "yarn publish --tag beta", | ||
"types:check": "tsc --noEmit --project tsconfig.check.json", | ||
"csb:install": "pnpm i -g pnpm@7", | ||
"csb:build": "pnpm install && pnpm build", | ||
"clean": "turbo run clean", | ||
"build": "turbo run build", | ||
"watch": "turbo run watch --parallel", | ||
"types:check": "turbo run types:check", | ||
"watch:core": "turbo run watch --filter=swr-core", | ||
"watch:infinite": "turbo run watch --filter=swr-inifinite", | ||
"watch:immutable": "turbo run watch --filter=swr-immutable", | ||
"watch:mutation": "turbo run watch --filter=swr-mutation", | ||
"watch:internal": "turbo run watch --filter=swr-internal", | ||
"build:core": "turbo run build --filter=swr-core", | ||
"build:infinite": "turbo run build --filter=swr-infinite", | ||
"build:immutable": "turbo run build --filter=swr-immutable", | ||
"build:mutation": "turbo run build --filter=swr-mutation", | ||
"build:internal": "turbo run build --filter=swr-internal", | ||
"prepublishOnly": "pnpm clean && pnpm build", | ||
"publish-beta": "pnpm publish --tag beta", | ||
"format": "prettier --write ./**/*.{ts,tsx}", | ||
"lint": "eslint . --ext .ts,.tsx --cache", | ||
"lint:fix": "yarn lint --fix", | ||
"lint:fix": "pnpm lint --fix", | ||
"coverage": "jest --coverage", | ||
@@ -92,3 +96,3 @@ "test": "tsc --noEmit -p test && jest" | ||
"hooks": { | ||
"pre-commit": "lint-staged && yarn types:check" | ||
"pre-commit": "lint-staged && pnpm types:check" | ||
} | ||
@@ -103,34 +107,34 @@ }, | ||
}, | ||
"resolutions": { | ||
"tslib": "2.3.0" | ||
}, | ||
"devDependencies": { | ||
"@types/use-sync-external-store": "^0.0.3", | ||
"@swc/core": "1.2.129", | ||
"@swc/jest": "0.2.17", | ||
"@swc/core": "1.2.186", | ||
"@swc/jest": "0.2.21", | ||
"@testing-library/jest-dom": "^5.16.4", | ||
"@testing-library/react": "^13.1.1", | ||
"@type-challenges/utils": "0.1.1", | ||
"@types/react": "^18.0.6", | ||
"@typescript-eslint/eslint-plugin": "5.8.0", | ||
"@typescript-eslint/parser": "5.8.0", | ||
"bunchee": "1.8.3", | ||
"eslint": "8.3.0", | ||
"eslint-config-prettier": "8.3.0", | ||
"eslint-plugin-jest-dom": "3.9.2", | ||
"eslint-plugin-react": "7.27.1", | ||
"eslint-plugin-react-hooks": "4.3.0", | ||
"eslint-plugin-testing-library": "5.0.0", | ||
"@types/jest": "^27.5.1", | ||
"@types/node": "^17.0.34", | ||
"@types/react": "^18.0.9", | ||
"@types/use-sync-external-store": "^0.0.3", | ||
"@typescript-eslint/eslint-plugin": "5.25.0", | ||
"@typescript-eslint/parser": "5.25.0", | ||
"bunchee": "1.8.5", | ||
"eslint": "8.15.0", | ||
"eslint-config-prettier": "8.5.0", | ||
"eslint-plugin-jest-dom": "4.0.1", | ||
"eslint-plugin-react": "7.30.0", | ||
"eslint-plugin-react-hooks": "4.5.0", | ||
"eslint-plugin-testing-library": "5.5.0", | ||
"husky": "2.4.1", | ||
"jest": "28.0.2", | ||
"jest-environment-jsdom": "28.0.2", | ||
"jest": "28.1.0", | ||
"jest-environment-jsdom": "28.1.0", | ||
"lint-staged": "8.2.1", | ||
"next": "^12.1.0", | ||
"npm-run-all": "4.1.5", | ||
"prettier": "2.5.0", | ||
"react": "^18.0.0", | ||
"react-dom": "^18.0.0", | ||
"next": "^12.1.6", | ||
"prettier": "2.6.2", | ||
"react": "^18.1.0", | ||
"react-dom": "^18.1.0", | ||
"rimraf": "3.0.2", | ||
"swr": "link:./", | ||
"typescript": "4.4.3" | ||
"swr": "workspace:*", | ||
"tslib": "2.4.0", | ||
"turbo": "^1.2.9", | ||
"typescript": "4.6.4" | ||
}, | ||
@@ -148,2 +152,5 @@ "peerDependencies": { | ||
}, | ||
"engines": { | ||
"pnpm": "7" | ||
}, | ||
"dependencies": { | ||
@@ -150,0 +157,0 @@ "use-sync-external-store": "^1.1.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
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
442429
58
5303
0
31