UNPKG

react-redux-query

Version:

React hooks and functions for SWR-style data fetching, backed by Redux

322 lines (321 loc) 19.2 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(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); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var __spreadArrays = (this && this.__spreadArrays) || function () { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useQueryState = exports.useQuery = exports.query = exports.ConfigContext = void 0; var react_1 = require("react"); var react_redux_1 = require("react-redux"); var actions_1 = require("./actions"); var fetchStateByKey = {}; exports.ConfigContext = react_1.createContext({}); /** * Calls fetcher and awaits response. Saves data to query branch at key and returns response. What is saved to Redux * depends on the value of response.queryData: * * - If response.queryData isn't set, save response * - If response.queryData isn't set, and response is null or undefined, don't save anything * - If response.queryData is set, save queryData * - If response.queryData is set but is null or undefined, don't save anything * * @param key - Key in query branch at which to store response * @param fetcher - Function that returns response with optional queryData property * @param options - Options object * @param options.dispatch - Dispatch function to send data to store (required) * @param options.updater - If passed, this function takes data currently at key, plus data in response, and returns * updated data to be saved at key * @param options.saveStaleResponse - If true, save response even if it's "stale" (false by default) * @param options.dedupe - If true, don't call fetcher if another request was recently sent for key * @param options.dedupeMs - If dedupe is true, dedupe behavior active for this many ms (2000 by default) * @param options.catchError - If true, any error thrown by fetcher is caught and assigned to queryState.error property * (true by default) * * @returns Response, or undefined if fetcher call gets deduped, or undefined if fetcher throws error */ function query(key, fetcher, options) { return __awaiter(this, void 0, void 0, function () { var dispatch, updater, _a, dedupe, _b, dedupeMs, _c, catchError, _d, saveStaleResponse, fetchMs, fetchMonoMs, fetchStateBefore, inFlightBefore, counter, requestId, _loop_1, state_1, response, error, e_1, afterMs, fetchState, inFlight, saveData, queryData; return __generator(this, function (_e) { switch (_e.label) { case 0: dispatch = options.dispatch, updater = options.updater, _a = options.dedupe, dedupe = _a === void 0 ? false : _a, _b = options.dedupeMs, dedupeMs = _b === void 0 ? 2000 : _b, _c = options.catchError, catchError = _c === void 0 ? true : _c, _d = options.saveStaleResponse, saveStaleResponse = _d === void 0 ? false : _d; fetchMs = Date.now(); fetchMonoMs = Math.round(performance.now()); fetchStateBefore = fetchStateByKey[key]; // Bail out if dedupe is true and another request was recently sent for key if (dedupe && fetchStateBefore && fetchMonoMs - fetchStateBefore.fetchMonoMs <= dedupeMs) return [2 /*return*/]; inFlightBefore = __spreadArrays(((fetchStateBefore === null || fetchStateBefore === void 0 ? void 0 : fetchStateBefore.inFlight) || [])); counter = 0; requestId = ''; _loop_1 = function () { var id = fetchMonoMs + "-" + counter; if (!inFlightBefore.find(function (data) { return data.id === id; })) { inFlightBefore.push({ id: id, fetchMonoMs: fetchMonoMs }); requestId = id; return "break"; } counter += 1; }; while (true) { state_1 = _loop_1(); if (state_1 === "break") break; } // Notify client that fetcher will be called fetchStateByKey[key] = { fetchMonoMs: fetchMonoMs, inFlight: inFlightBefore }; dispatch(actions_1.updateQueryState({ key: key, state: { fetchMs: fetchMs, inFlight: inFlightBefore } })); response = undefined; _e.label = 1; case 1: _e.trys.push([1, 3, , 4]); return [4 /*yield*/, fetcher()]; case 2: response = _e.sent(); return [3 /*break*/, 4]; case 3: e_1 = _e.sent(); error = e_1 || {}; return [3 /*break*/, 4]; case 4: afterMs = Date.now(); fetchState = fetchStateByKey[key]; inFlight = ((fetchState === null || fetchState === void 0 ? void 0 : fetchState.inFlight) || []).filter(function (data) { return data.id !== requestId; }); fetchStateByKey[key] = { fetchMonoMs: (fetchState === null || fetchState === void 0 ? void 0 : fetchState.fetchMonoMs) || fetchMonoMs, inFlight: inFlight }; // If error was thrown, notify client and bail out if (error) { dispatch(actions_1.updateQueryState({ key: key, state: { error: error, errorMs: afterMs, inFlight: inFlight } })); if (catchError) return [2 /*return*/]; throw error; } saveData = function (data) { if (updater) { // Results in only one rerender, not two: https://react-redux.js.org/api/batch#batch react_redux_1.batch(function () { dispatch(actions_1.updateQueryState({ key: key, state: { dataMs: afterMs, goodFetchMonoMs: fetchMonoMs, inFlight: inFlight }, })); // @ts-ignore; newData property only for internal use, including it in Update interface would just be confusing dispatch(actions_1.update({ key: key, updater: updater, newData: data })); }); } else { dispatch(actions_1.updateQueryState({ key: key, state: { data: __assign({}, data), dataMs: afterMs, goodFetchMonoMs: fetchMonoMs, inFlight: inFlight }, options: { saveStaleResponse: saveStaleResponse }, })); } }; if (response === null || response === void 0 ? void 0 : response.hasOwnProperty('queryData')) { queryData = response.queryData; if (queryData !== null && queryData !== undefined) { // If response.queryData is set and is neither null nor undefined, save response.queryData saveData(queryData); } else { // If response.queryData is set but is null or undefined, save response as error dispatch(actions_1.updateQueryState({ key: key, state: { error: __assign({}, response), errorMs: afterMs, inFlight: inFlight }, })); } } else if (response !== null && response !== undefined) { // If saveData.queryData isn't set, only save response if it's neither null nor undefined saveData(response); } return [2 /*return*/, response]; } }); }); } exports.query = query; /** * Hook calls fetcher and saves data to query branch at key. Immediately returns query state (including data, dataMs, * dataMonoMs) at key, and subscribes to changes in this query state. * * Data is only refetched if key, intervalMs, or refetchKey changes; passing in a new fetcher function alone doesn't * refetch data. * * @param key - Key in query branch at which to store data; if null/undefined, fetcher not called * @param fetcher - Function that returns response with optional queryData property; if null/undefined, fetcher not * called * @param options - Options object * @param options.intervalMs - Interval between end of fetcher call and next fetcher call * @param options.intervalRedefineFetcher - If true, fetcher is redefined each time it's called on interval, by forcing * component to rerender (false by default) * @param options.noRefetch - If true, don't refetch if there's already data at key * @param options.noRefetchMs - If noRefetch is true, noRefetch behavior active for this many ms (forever by default) * @param options.refetchKey - Pass in new value to force refetch without changing key * @param options.updater - If passed, this function takes data currently at key, plus data in response, and returns * updated data to be saved at key * @param options.saveStaleResponse - If true, save response even if it's "stale" (false by default) * @param options.dedupe - If true, don't call fetcher if another request was recently sent for key * @param options.dedupeMs - If dedupe is true, dedupe behavior active for this many ms (2000 by default) * @param options.catchError - If true, any error thrown by fetcher is caught and assigned to queryState.error property * (true by default) * @param options.stateKeys - Additional keys in query state to include in return value (only data and dataMs included * by default) * @param options.compare - Equality function compares previous query state with next query state; if it returns false, * component rerenders, else it doesn't; uses shallowEqual by default * * @returns Query state at key, with subset of properties specified by stateKeys */ function useQuery(key, fetcher, options) { var _this = this; var _a; if (options === void 0) { options = {}; } var stateKeys = options.stateKeys, compare = options.compare, _b = options.intervalMs, intervalMs = _b === void 0 ? 0 : _b, intervalRedefineFetcher = options.intervalRedefineFetcher, _c = options.noRefetch, noRefetch = _c === void 0 ? false : _c, _d = options.noRefetchMs, noRefetchMs = _d === void 0 ? 0 : _d, refetchKey = options.refetchKey, updater = options.updater, rest = __rest(options, ["stateKeys", "compare", "intervalMs", "intervalRedefineFetcher", "noRefetch", "noRefetchMs", "refetchKey", "updater"]); var config = react_1.useContext(exports.ConfigContext); var dispatch = react_redux_1.useDispatch(); var _e = react_1.useState(0), intervalId = _e[0], setIntervalId = _e[1]; var intervalTimeoutIdRef = react_1.useRef(); var redefineFetcher = (_a = intervalRedefineFetcher !== null && intervalRedefineFetcher !== void 0 ? intervalRedefineFetcher : config.intervalRedefineFetcher) !== null && _a !== void 0 ? _a : false; var queryState = useQueryState(key, { stateKeys: stateKeys, compare: compare }); react_1.useEffect(function () { // If we have pending interval call to query, clear it; we're about to query again anyway clearTimeout(intervalTimeoutIdRef.current); // Should we return early? if (queryState.data && noRefetch) { // Defensive code; can't be sure dataMs is a number (user could use their own reducer) if (noRefetchMs <= 0 || typeof queryState.dataMs !== 'number') return; // User specified a positive value for noRefetchMs; determine if we should we refetch or not if (Date.now() - queryState.dataMs <= noRefetchMs) return; } if (key === null || key === undefined || !fetcher) return; var doQuery = function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, query(key, fetcher, __assign(__assign(__assign({}, config), rest), { updater: updater, dispatch: dispatch }))]; case 1: _a.sent(); if (intervalMs <= 0) return [2 /*return*/]; // Force this effect to run again after intervalMs; "pseudo-recursive" call means call stack doesn't grow intervalTimeoutIdRef.current = window.setTimeout(function () { if (redefineFetcher) setIntervalId(function (id) { return id + 1; }); else doQuery(); }, intervalMs); return [2 /*return*/]; } }); }); }; doQuery(); }, [key, intervalMs, redefineFetcher, refetchKey, intervalId]); // eslint-disable-line // Also clear interval when component unmounts react_1.useEffect(function () { return function () { clearTimeout(intervalTimeoutIdRef.current); }; }, []); return queryState; } exports.useQuery = useQuery; /** * Hook retrieves query state for key from from Redux, and subscribes to changes in query state. State object includes * only data and dataMs properties by default, and subscribes to changes in these properties only, unless additional * stateKeys passed. * * @param key - Key in query branch * @param options - Options object * @param options.stateKeys - Additional keys in query state to include in return value (only data and dataMs included * by default) * @param options.compare - Equality function compares previous query state with next query state; if it returns false, * component rerenders, else it doesn't; uses shallowEqual by default * * @returns Query state at key, with subset of properties specified by stateKeys */ function useQueryState(key, options) { if (options === void 0) { options = {}; } // K before D in useQueryState signature, because K can be inferred, while D can't var _a = react_1.useContext(exports.ConfigContext), _b = _a.branchName, branchName = _b === void 0 ? 'query' : _b, configCompare = _a.compare; return react_redux_1.useSelector(function (state) { var stateKeys = (options.stateKeys || []); // Return type picks QueryState properties specified in options.stateKeys, in addition to data and dataMs var partialQueryState = {}; if (!key) return partialQueryState; var queryState = state[branchName][key]; if (!queryState) return partialQueryState; partialQueryState.data = queryState.data; partialQueryState.dataMs = queryState.dataMs; for (var _i = 0, stateKeys_1 = stateKeys; _i < stateKeys_1.length; _i++) { var stateKey = stateKeys_1[_i]; // @ts-ignore partialQueryState[stateKey] = queryState[stateKey]; } return partialQueryState; }, options.compare || configCompare || react_redux_1.shallowEqual); } exports.useQueryState = useQueryState;