UNPKG

ra-core

Version:

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

203 lines 11.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 __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.useUpdateMany = void 0; var react_query_1 = require("@tanstack/react-query"); var useDataProvider_1 = require("./useDataProvider"); var useMutationWithMutationMode_1 = require("./useMutationWithMutationMode"); var util_1 = require("../util"); /** * Get a callback to call the dataProvider.updateMany() method, the result and the loading state. * * @param {string} resource * @param {Params} params The updateMany parameters { ids, data, meta } * @param {Object} options Options object to pass to the queryClient. * May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } } * May include a mutation mode (optimistic/pessimistic/undoable), e.g. { mutationMode: 'undoable' } * * @typedef Params * @prop params.ids The resource identifiers, e.g. [123, 456] * @prop params.data The updates to merge into the record, e.g. { views: 10 } * @prop params.meta Optional meta parameters * * @returns The current mutation state. Destructure as [updateMany, { data, error, isPending }]. * * The return value updates according to the request state: * * - initial: [updateMany, { isPending: false, isIdle: true }] * - start: [updateMany, { isPending: true }] * - success: [updateMany, { data: [data from response], isPending: false, isSuccess: true }] * - error: [updateMany, { error: [error from response], isPending: false, isError: true }] * * The updateMany() function must be called with a resource and a parameter object: updateMany(resource, { ids, data, previousData }, options) * * This hook uses react-query useMutation under the hood. * This means the state object contains mutate, isIdle, reset and other react-query methods. * * @see https://tanstack.com/query/v5/docs/react/reference/useMutation * * @example // set params when calling the updateMany callback * * import { useUpdateMany, useListContext } from 'react-admin'; * * const BulkResetViewsButton = () => { * const { selectedIds } = useListContext(); * const [updateMany, { isPending, error }] = useUpdateMany(); * const handleClick = () => { * updateMany('posts', { ids: selectedIds, data: { views: 0 } }); * } * if (error) { return <p>ERROR</p>; } * return <button disabled={isPending} onClick={handleClick}>Reset views</button>; * }; * * @example // set params when calling the hook * * import { useUpdateMany, useListContext } from 'react-admin'; * * const BulkResetViewsButton = () => { * const { selectedIds } = useListContext(); * const [updateMany, { isPending, error }] = useUpdateMany('posts', { ids: selectedIds, data: { views: 0 } }); * if (error) { return <p>ERROR</p>; } * return <button disabled={isPending} onClick={() => updateMany()}>Reset views</button>; * }; */ var useUpdateMany = function (resource, params, options) { if (params === void 0) { params = {}; } if (options === void 0) { options = {}; } var dataProvider = (0, useDataProvider_1.useDataProvider)(); var queryClient = (0, react_query_1.useQueryClient)(); var _a = options.mutationMode, mutationMode = _a === void 0 ? 'pessimistic' : _a, getMutateWithMiddlewares = options.getMutateWithMiddlewares, mutationOptions = __rest(options, ["mutationMode", "getMutateWithMiddlewares"]); var dataProviderUpdateMany = (0, util_1.useEvent)(function (resource, params) { return dataProvider.updateMany(resource, params); }); var _b = (0, useMutationWithMutationMode_1.useMutationWithMutationMode)(__assign({ resource: resource }, params), __assign(__assign({}, mutationOptions), { mutationKey: [resource, 'updateMany', params], mutationMode: mutationMode, mutationFn: function (_a) { var resource = _a.resource, params = __rest(_a, ["resource"]); if (resource == null) { throw new Error('useUpdateMany mutation requires a resource'); } if (params.ids == null) { throw new Error('useUpdateMany mutation requires an array of ids'); } if (!params.data) { throw new Error('useUpdateMany mutation requires a non-empty data object'); } return dataProviderUpdateMany(resource, params); }, updateCache: function (_a, _b) { var _c; var resource = _a.resource, params = __rest(_a, ["resource"]); var mutationMode = _b.mutationMode; // hack: only way to tell react-query not to fetch this query for the next 5 seconds // because setQueryData doesn't accept a stale time option var updatedAt = mutationMode === 'undoable' ? Date.now() + 1000 * 5 : Date.now(); // Stringify and parse the data to remove undefined values. // If we don't do this, an update with { id: undefined } as payload // would remove the id from the record, which no real data provider does. var clonedData = (params === null || params === void 0 ? void 0 : params.data) ? JSON.parse(JSON.stringify(params === null || params === void 0 ? void 0 : params.data)) : undefined; var updateColl = function (old) { var _a; if (!old) return old; var newCollection = __spreadArray([], old, true); ((_a = params === null || params === void 0 ? void 0 : params.ids) !== null && _a !== void 0 ? _a : []).forEach(function (id) { // eslint-disable-next-line eqeqeq var index = old.findIndex(function (record) { return record.id == id; }); if (index === -1) { return; } newCollection = __spreadArray(__spreadArray(__spreadArray([], newCollection.slice(0, index), true), [ __assign(__assign({}, newCollection[index]), clonedData) ], false), newCollection.slice(index + 1), true); }); return newCollection; }; ((_c = params === null || params === void 0 ? void 0 : params.ids) !== null && _c !== void 0 ? _c : []).forEach(function (id) { queryClient.setQueryData([ resource, 'getOne', { id: String(id), meta: params === null || params === void 0 ? void 0 : params.meta }, ], function (record) { return (__assign(__assign({}, record), clonedData)); }, { updatedAt: updatedAt }); }); queryClient.setQueriesData({ queryKey: [resource, 'getList'] }, function (res) { return res && res.data ? __assign(__assign({}, res), { data: updateColl(res.data) }) : res; }, { updatedAt: updatedAt }); queryClient.setQueriesData({ queryKey: [resource, 'getInfiniteList'] }, function (res) { return res && res.pages ? __assign(__assign({}, res), { pages: res.pages.map(function (page) { return (__assign(__assign({}, page), { data: updateColl(page.data) })); }) }) : res; }, { updatedAt: updatedAt }); queryClient.setQueriesData({ queryKey: [resource, 'getMany'] }, function (coll) { return coll && coll.length > 0 ? updateColl(coll) : coll; }, { updatedAt: updatedAt }); queryClient.setQueriesData({ queryKey: [resource, 'getManyReference'] }, function (res) { return res && res.data ? __assign(__assign({}, res), { data: updateColl(res.data) }) : res; }, { updatedAt: updatedAt }); return params === null || params === void 0 ? void 0 : params.ids; }, getQueryKeys: function (_a) { var resource = _a.resource; var queryKeys = [ [resource, 'getOne'], [resource, 'getList'], [resource, 'getInfiniteList'], [resource, 'getMany'], [resource, 'getManyReference'], ]; return queryKeys; }, getMutateWithMiddlewares: function (mutationFn) { if (getMutateWithMiddlewares) { // Immediately get the function with middlewares applied so that even if the middlewares gets unregistered (because of a redirect for instance), // we still have them applied when users have called the mutate function. var mutateWithMiddlewares_1 = getMutateWithMiddlewares(dataProviderUpdateMany.bind(dataProvider)); return function (args) { // This is necessary to avoid breaking changes in useUpdateMany: // The mutation function must have the same signature as before (resource, params) and not ({ resource, params }) var resource = args.resource, params = __rest(args, ["resource"]); return mutateWithMiddlewares_1(resource, params); }; } return function (args) { return mutationFn(args); }; } })), mutate = _b[0], mutationResult = _b[1]; var updateMany = (0, util_1.useEvent)(function (callTimeResource, callTimeParams, callTimeOptions) { if (callTimeResource === void 0) { callTimeResource = resource; } if (callTimeParams === void 0) { callTimeParams = {}; } if (callTimeOptions === void 0) { callTimeOptions = {}; } return mutate(__assign({ resource: callTimeResource }, callTimeParams), callTimeOptions); }); return [updateMany, mutationResult]; }; exports.useUpdateMany = useUpdateMany; //# sourceMappingURL=useUpdateMany.js.map