UNPKG

ra-core

Version:

Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React

338 lines 20.1 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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["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 (g && (g = 0, op[0] && (_ = 0)), _) 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 __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useMutationWithMutationMode = void 0; var react_1 = require("react"); var react_query_1 = require("@tanstack/react-query"); var useAddUndoableMutation_1 = require("./undo/useAddUndoableMutation"); var util_1 = require("../util"); var useMutationWithMutationMode = function (params, options) { if (params === void 0) { params = {}; } var queryClient = (0, react_query_1.useQueryClient)(); var addUndoableMutation = (0, useAddUndoableMutation_1.useAddUndoableMutation)(); var mutationKey = options.mutationKey, _a = options.mutationMode, mutationMode = _a === void 0 ? 'pessimistic' : _a, mutationFn = options.mutationFn, getMutateWithMiddlewares = options.getMutateWithMiddlewares, updateCache = options.updateCache, getQueryKeys = options.getQueryKeys, onUndo = options.onUndo, mutationOptions = __rest(options, ["mutationKey", "mutationMode", "mutationFn", "getMutateWithMiddlewares", "updateCache", "getQueryKeys", "onUndo"]); if (mutationFn == null) { throw new Error('useMutationWithMutationMode mutation requires a mutationFn'); } var mutationFnEvent = (0, util_1.useEvent)(mutationFn); var updateCacheEvent = (0, util_1.useEvent)(updateCache); var getQueryKeysEvent = (0, util_1.useEvent)(getQueryKeys); var getSnapshotEvent = (0, util_1.useEvent)( /** * Snapshot the previous values via queryClient.getQueriesData() * * The snapshotData ref will contain an array of tuples [query key, associated data] * * @example * [ * [['posts', 'getList'], { data: [{ id: 1, title: 'Hello' }], total: 1 }], * [['posts', 'getMany'], [{ id: 1, title: 'Hello' }]], * ] * * @see https://tanstack.com/query/v5/docs/react/reference/QueryClient#queryclientgetqueriesdata */ function (queryKeys) { return queryKeys.reduce(function (prev, queryKey) { return prev.concat(queryClient.getQueriesData({ queryKey: queryKey })); }, []); }); var onUndoEvent = (0, util_1.useEvent)(onUndo !== null && onUndo !== void 0 ? onUndo : noop); var getMutateWithMiddlewaresEvent = (0, util_1.useEvent)(getMutateWithMiddlewares !== null && getMutateWithMiddlewares !== void 0 ? getMutateWithMiddlewares : noop); var mode = (0, react_1.useRef)(mutationMode); (0, react_1.useEffect)(function () { mode.current = mutationMode; }, [mutationMode]); // This ref won't be updated when params change in an effect, only when the mutate callback is called (See L247) // This ensures that for undoable and optimistic mutations, the params are not changed by side effects (unselectAll for instance) // _after_ the mutate function has been called, while keeping the ability to change declaration time params _until_ the mutation is called. var paramsRef = (0, react_1.useRef)(params); // Ref that stores the snapshot of the state before the mutation to allow reverting it var snapshot = (0, react_1.useRef)([]); // Ref that stores the mutation with middlewares to avoid losing them if the calling component is unmounted var mutateWithMiddlewares = (0, react_1.useRef)(mutationFnEvent); // We need to store the call-time onError and onSettled in refs to be able to call them in the useMutation hook even // when the calling component is unmounted var callTimeOnError = (0, react_1.useRef)(); var callTimeOnSettled = (0, react_1.useRef)(); // We don't need to keep a ref on the onSuccess callback as we call it ourselves for optimistic and // undoable mutations. There is a limitation though: if one of the side effects applied by the onSuccess callback // unmounts the component that called the useUpdate hook (redirect for instance), it must be the last one applied, // otherwise the other side effects may not applied. var hasCallTimeOnSuccess = (0, react_1.useRef)(false); var mutation = (0, react_query_1.useMutation)(__assign(__assign({ mutationKey: mutationKey, mutationFn: function (params) { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { if (params == null) { throw new Error('useMutationWithMutationMode mutation requires parameters'); } return [2 /*return*/, (mutateWithMiddlewares .current(params) // Middlewares expect the data property of the dataProvider response .then(function (_a) { var data = _a.data; return data; }))]; }); }); } }, mutationOptions), { onMutate: function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return __awaiter(void 0, void 0, void 0, function () { var userContext; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!mutationOptions.onMutate) return [3 /*break*/, 2]; return [4 /*yield*/, mutationOptions.onMutate.apply(mutationOptions, args)]; case 1: userContext = (_a.sent()) || {}; return [2 /*return*/, __assign({ snapshot: snapshot.current }, userContext)]; case 2: // Return a context object with the snapshot value return [2 /*return*/, { snapshot: snapshot.current }]; } }); }); }, onError: function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (mode.current === 'optimistic' || mode.current === 'undoable') { var onMutateResult = args[2]; // If the mutation fails, use the context returned from onMutate to rollback onMutateResult.snapshot.forEach(function (_a) { var key = _a[0], value = _a[1]; queryClient.setQueryData(key, value); }); } if (callTimeOnError.current) { return callTimeOnError.current.apply(callTimeOnError, args); } if (mutationOptions.onError) { return mutationOptions.onError.apply(mutationOptions, args); } // call-time error callback is executed by react-query }, onSuccess: function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (mode.current === 'pessimistic') { var data = args[0], variables = args[1]; // update the getOne and getList query cache with the new result updateCacheEvent(__assign(__assign({}, paramsRef.current), variables), { mutationMode: mode.current, }, data); if (mutationOptions.onSuccess && !hasCallTimeOnSuccess.current) { mutationOptions.onSuccess.apply(mutationOptions, args); } } }, onSettled: function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (mode.current === 'optimistic' || mode.current === 'undoable') { var variables = args[2]; // Always refetch after error or success: getQueryKeysEvent(__assign(__assign({}, paramsRef.current), variables), { mutationMode: mode.current, }).forEach(function (queryKey) { queryClient.invalidateQueries({ queryKey: queryKey }); }); } if (callTimeOnSettled.current) { return callTimeOnSettled.current.apply(callTimeOnSettled, args); } if (mutationOptions.onSettled) { return mutationOptions.onSettled.apply(mutationOptions, args); } } })); var mutate = function () { var args_1 = []; for (var _i = 0; _i < arguments.length; _i++) { args_1[_i] = arguments[_i]; } return __awaiter(void 0, __spreadArray([], args_1, true), void 0, function (callTimeParams, callTimeOptions) { var mutationMode, _a, returnPromise, onError, onSettled, onSuccess, otherCallTimeOptions, optimisticResult; if (callTimeParams === void 0) { callTimeParams = {}; } if (callTimeOptions === void 0) { callTimeOptions = {}; } return __generator(this, function (_b) { switch (_b.label) { case 0: mutationMode = callTimeOptions.mutationMode, _a = callTimeOptions.returnPromise, returnPromise = _a === void 0 ? mutationOptions.returnPromise : _a, onError = callTimeOptions.onError, onSettled = callTimeOptions.onSettled, onSuccess = callTimeOptions.onSuccess, otherCallTimeOptions = __rest(callTimeOptions, ["mutationMode", "returnPromise", "onError", "onSettled", "onSuccess"]); // store the hook time params *at the moment of the call* // because they may change afterwards, which would break the undoable mode // as the previousData would be overwritten by the optimistic update paramsRef.current = params; // Store the mutation with middlewares to avoid losing them if the calling component is unmounted if (getMutateWithMiddlewares) { mutateWithMiddlewares.current = getMutateWithMiddlewaresEvent(function (params) { return mutationFnEvent(params); }); } else { mutateWithMiddlewares.current = mutationFnEvent; } // We need to keep the onSuccess callback here and not in the useMutation for undoable mutations hasCallTimeOnSuccess.current = !!onSuccess; // We need to store the onError and onSettled callbacks here to be able to call them in the useMutation hook // so that they are called even when the calling component is unmounted callTimeOnError.current = onError; callTimeOnSettled.current = onSettled; if (mutationMode) { mode.current = mutationMode; } if (returnPromise && mode.current !== 'pessimistic') { console.warn('The returnPromise parameter can only be used if the mutationMode is set to pessimistic'); } snapshot.current = getSnapshotEvent(getQueryKeysEvent(__assign(__assign({}, paramsRef.current), callTimeParams), { mutationMode: mode.current, })); if (mode.current === 'pessimistic') { if (returnPromise) { return [2 /*return*/, mutation.mutateAsync(__assign(__assign({}, paramsRef.current), callTimeParams), __assign({ onSuccess: onSuccess }, otherCallTimeOptions))]; } return [2 /*return*/, mutation.mutate(__assign(__assign({}, paramsRef.current), callTimeParams), __assign({ onSuccess: onSuccess }, otherCallTimeOptions))]; } // Cancel any outgoing re-fetches (so they don't overwrite our optimistic update) return [4 /*yield*/, Promise.all(snapshot.current.map(function (_a) { var queryKey = _a[0]; return queryClient.cancelQueries({ queryKey: queryKey }); }))]; case 1: // Cancel any outgoing re-fetches (so they don't overwrite our optimistic update) _b.sent(); optimisticResult = updateCacheEvent(__assign(__assign({}, paramsRef.current), callTimeParams), { mutationMode: mode.current, }, undefined); // run the success callbacks during the next tick setTimeout(function () { if (onSuccess) { onSuccess(optimisticResult, __assign(__assign({}, paramsRef.current), callTimeParams), { snapshot: snapshot.current, }, { client: queryClient, mutationKey: mutationKey, meta: mutationOptions.meta, }); } else if (mutationOptions.onSuccess && !hasCallTimeOnSuccess.current) { mutationOptions.onSuccess(optimisticResult, __assign(__assign({}, paramsRef.current), callTimeParams), { snapshot: snapshot.current, }, { client: queryClient, mutationKey: mutationKey, meta: mutationOptions.meta, }); } }, 0); if (mode.current === 'optimistic') { // call the mutate method without success side effects return [2 /*return*/, mutation.mutate(__assign(__assign({}, paramsRef.current), callTimeParams))]; } else { // Undoable mutation: add the mutation to the undoable queue. // The Notification component will dequeue it when the user confirms or cancels the message. addUndoableMutation(function (_a) { var isUndo = _a.isUndo; if (isUndo) { if (onUndo) { onUndoEvent(__assign(__assign({}, paramsRef.current), callTimeParams), { mutationMode: mode.current, }); } // rollback snapshot.current.forEach(function (_a) { var key = _a[0], value = _a[1]; queryClient.setQueryData(key, value); }); } else { // call the mutate method without success side effects mutation.mutate(__assign(__assign({}, paramsRef.current), callTimeParams)); } }); } return [2 /*return*/]; } }); }); }; var mutationResult = (0, react_1.useMemo)(function () { return (__assign({ isLoading: mutation.isPending }, mutation)); }, [mutation]); return [(0, util_1.useEvent)(mutate), mutationResult]; }; exports.useMutationWithMutationMode = useMutationWithMutationMode; var noop = function () { }; //# sourceMappingURL=useMutationWithMutationMode.js.map