react-query
Version:
Hooks for managing, caching and syncing asynchronous and remote data in React
193 lines (158 loc) • 6.21 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.ReactQueryPersistLocalStorageExperimental = {}));
}(this, (function (exports) { 'use strict';
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
// TYPES
// FUNCTIONS
function dehydrateMutation(mutation) {
return {
mutationKey: mutation.options.mutationKey,
state: mutation.state
};
} // Most config is not dehydrated but instead meant to configure again when
// consuming the de/rehydrated data, typically with useQuery on the client.
// Sometimes it might make sense to prefetch data on the server and include
// in the html-payload, but not consume it on the initial render.
function dehydrateQuery(query) {
return {
state: query.state,
queryKey: query.queryKey,
queryHash: query.queryHash
};
}
function defaultShouldDehydrateMutation(mutation) {
return mutation.state.isPaused;
}
function defaultShouldDehydrateQuery(query) {
return query.state.status === 'success';
}
function dehydrate(client, options) {
var _options, _options2;
options = options || {};
var mutations = [];
var queries = [];
if (((_options = options) == null ? void 0 : _options.dehydrateMutations) !== false) {
var shouldDehydrateMutation = options.shouldDehydrateMutation || defaultShouldDehydrateMutation;
client.getMutationCache().getAll().forEach(function (mutation) {
if (shouldDehydrateMutation(mutation)) {
mutations.push(dehydrateMutation(mutation));
}
});
}
if (((_options2 = options) == null ? void 0 : _options2.dehydrateQueries) !== false) {
var shouldDehydrateQuery = options.shouldDehydrateQuery || defaultShouldDehydrateQuery;
client.getQueryCache().getAll().forEach(function (query) {
if (shouldDehydrateQuery(query)) {
queries.push(dehydrateQuery(query));
}
});
}
return {
mutations: mutations,
queries: queries
};
}
function hydrate(client, dehydratedState, options) {
if (typeof dehydratedState !== 'object' || dehydratedState === null) {
return;
}
var mutationCache = client.getMutationCache();
var queryCache = client.getQueryCache();
var mutations = dehydratedState.mutations || [];
var queries = dehydratedState.queries || [];
mutations.forEach(function (dehydratedMutation) {
var _options$defaultOptio;
mutationCache.build(client, _extends({}, options == null ? void 0 : (_options$defaultOptio = options.defaultOptions) == null ? void 0 : _options$defaultOptio.mutations, {
mutationKey: dehydratedMutation.mutationKey
}), dehydratedMutation.state);
});
queries.forEach(function (dehydratedQuery) {
var _options$defaultOptio2;
var query = queryCache.get(dehydratedQuery.queryHash); // Do not hydrate if an existing query exists with newer data
if (query) {
if (query.state.dataUpdatedAt < dehydratedQuery.state.dataUpdatedAt) {
query.setState(dehydratedQuery.state);
}
return;
} // Restore query
queryCache.build(client, _extends({}, options == null ? void 0 : (_options$defaultOptio2 = options.defaultOptions) == null ? void 0 : _options$defaultOptio2.queries, {
queryKey: dehydratedQuery.queryKey,
queryHash: dehydratedQuery.queryHash
}), dehydratedQuery.state);
});
}
function persistWithLocalStorage(queryClient, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$localStorageKey = _ref.localStorageKey,
localStorageKey = _ref$localStorageKey === void 0 ? "REACT_QUERY_OFFLINE_CACHE" : _ref$localStorageKey,
_ref$throttleTime = _ref.throttleTime,
throttleTime = _ref$throttleTime === void 0 ? 1000 : _ref$throttleTime,
_ref$maxAge = _ref.maxAge,
maxAge = _ref$maxAge === void 0 ? 1000 * 60 * 60 * 24 : _ref$maxAge,
_ref$buster = _ref.buster,
buster = _ref$buster === void 0 ? '' : _ref$buster;
if (typeof window !== 'undefined') {
// Subscribe to changes
var saveCache = throttle(function () {
var storageCache = {
buster: buster,
timestamp: Date.now(),
cacheState: dehydrate(queryClient)
};
localStorage.setItem(localStorageKey, JSON.stringify(storageCache));
}, throttleTime);
queryClient.getQueryCache().subscribe(saveCache); // Attempt restore
var cacheStorage = localStorage.getItem(localStorageKey);
if (!cacheStorage) {
return;
}
var cache = JSON.parse(cacheStorage);
if (cache.timestamp) {
var expired = Date.now() - cache.timestamp > maxAge;
var busted = cache.buster !== buster;
if (expired || busted) {
localStorage.removeItem(localStorageKey);
} else {
hydrate(queryClient, cache.cacheState);
}
} else {
localStorage.removeItem(localStorageKey);
}
}
}
function throttle(func, wait) {
if (wait === void 0) {
wait = 100;
}
var timer = null;
return function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (timer === null) {
timer = setTimeout(function () {
func.apply(void 0, args);
timer = null;
}, wait);
}
};
}
exports.persistWithLocalStorage = persistWithLocalStorage;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=persist-localstorage-experimental.development.js.map