ra-core
Version:
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
210 lines • 11.4 kB
JavaScript
;
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.useUpdate = 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.update() method, the result and the loading state.
*
* @param {string} resource
* @param {Params} params The update parameters { id, data, previousData, 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.id The resource identifier, e.g. 123
* @prop params.data The updates to merge into the record, e.g. { views: 10 }
* @prop params.previousData The record before the update is applied
* @prop params.meta Optional meta data
*
* @returns The current mutation state. Destructure as [update, { data, error, isPending }].
*
* The return value updates according to the request state:
*
* - initial: [update, { isPending: false, isIdle: true }]
* - start: [update, { isPending: true }]
* - success: [update, { data: [data from response], isPending: false, isSuccess: true }]
* - error: [update, { error: [error from response], isPending: false, isError: true }]
*
* The update() function must be called with a resource and a parameter object: update(resource, { id, 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://react-query-v3.tanstack.com/reference/useMutation
*
* @example // set params when calling the update callback
*
* import { useUpdate, useRecordContext } from 'react-admin';
*
* const IncreaseLikeButton = () => {
* const record = useRecordContext();
* const diff = { likes: record.likes + 1 };
* const [update, { isPending, error }] = useUpdate();
* const handleClick = () => {
* update('likes', { id: record.id, data: diff, previousData: record })
* }
* if (error) { return <p>ERROR</p>; }
* return <button disabled={isPending} onClick={handleClick}>Like</div>;
* };
*
* @example // set params when calling the hook
*
* import { useUpdate, useRecordContext } from 'react-admin';
*
* const IncreaseLikeButton = () => {
* const record = useRecordContext();
* const diff = { likes: record.likes + 1 };
* const [update, { isPending, error }] = useUpdate('likes', { id: record.id, data: diff, previousData: record });
* if (error) { return <p>ERROR</p>; }
* return <button disabled={isPending} onClick={() => update()}>Like</button>;
* };
*
* @example // TypeScript
* const [update, { data }] = useUpdate<Product>('products', { id, data: diff, previousData: product });
* \-- data is Product
*/
var useUpdate = 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 dataProviderUpdate = (0, util_1.useEvent)(function (resource, params) {
return dataProvider.update(resource, params);
});
var _b = (0, useMutationWithMutationMode_1.useMutationWithMutationMode)(__assign({ resource: resource }, params), __assign(__assign({}, mutationOptions), { mutationKey: [resource, 'update', params], mutationMode: mutationMode, mutationFn: function (_a) {
var resource = _a.resource, params = __rest(_a, ["resource"]);
if (resource == null) {
throw new Error('useUpdate mutation requires a resource');
}
if (params.id == null) {
throw new Error('useUpdate mutation requires a non-empty id');
}
if (!params.data) {
throw new Error('useUpdate mutation requires a non-empty data object');
}
return dataProviderUpdate(resource, params);
}, updateCache: function (_a, _b, result) {
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 now = Date.now();
var updatedAt = mutationMode === 'undoable' ? now + 5 * 1000 : 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 = JSON.parse(JSON.stringify(mutationMode === 'pessimistic' ? result : params === null || params === void 0 ? void 0 : params.data));
var updateColl = function (old) {
if (!old)
return old;
var index = old.findIndex(
// eslint-disable-next-line eqeqeq
function (record) { return record.id == (params === null || params === void 0 ? void 0 : params.id); });
if (index === -1) {
return old;
}
return __spreadArray(__spreadArray(__spreadArray([], old.slice(0, index), true), [
__assign(__assign({}, old[index]), clonedData)
], false), old.slice(index + 1), true);
};
var previousRecord = queryClient.getQueryData([
resource,
'getOne',
{ id: String(params === null || params === void 0 ? void 0 : params.id), meta: params === null || params === void 0 ? void 0 : params.meta },
]);
queryClient.setQueryData([
resource,
'getOne',
{ id: String(params === null || params === void 0 ? void 0 : params.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 });
var optimisticResult = __assign(__assign({}, previousRecord), clonedData);
return optimisticResult;
}, getQueryKeys: function (_a) {
var resource = _a.resource, params = __rest(_a, ["resource"]);
var queryKeys = [
[
resource,
'getOne',
{ id: String(params === null || params === void 0 ? void 0 : params.id), meta: params === null || params === void 0 ? void 0 : params.meta },
],
[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(dataProviderUpdate.bind(dataProvider));
return function (args) {
// This is necessary to avoid breaking changes in useUpdate:
// 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 update = (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 [update, mutationResult];
};
exports.useUpdate = useUpdate;
//# sourceMappingURL=useUpdate.js.map