ra-core
Version:
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
179 lines • 9.08 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;
};
import { useQueryClient, } from '@tanstack/react-query';
import { useDataProvider } from "./useDataProvider.js";
import { useEvent } from "../util/index.js";
import { useMutationWithMutationMode, } from "./useMutationWithMutationMode.js";
/**
* Get a callback to call the dataProvider.create() method, the result and the loading state.
*
* @param {string} resource
* @param {Params} params The create parameters { data }
* @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(); } }
*
* @typedef Params
* @prop params.data The record to create, e.g. { title: 'hello, world' }
*
* @returns The current mutation state. Destructure as [create, { data, error, isPending }].
*
* The return value updates according to the request state:
*
* - initial: [create, { isPending: false, isIdle: true }]
* - start: [create, { isPending: true }]
* - success: [create, { data: [data from response], isPending: false, isSuccess: true }]
* - error: [create, { error: [error from response], isPending: false, isError: true }]
*
* The create() function must be called with a resource and a parameter object: create(resource, { data, meta }, 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 create callback
*
* import { useCreate, useRecordContext } from 'react-admin';
*
* const LikeButton = () => {
* const record = useRecordContext();
* const like = { postId: record.id };
* const [create, { isPending, error }] = useCreate();
* const handleClick = () => {
* create('likes', { data: like })
* }
* if (error) { return <p>ERROR</p>; }
* return <button disabled={isPending} onClick={handleClick}>Like</button>;
* };
*
* @example // set params when calling the hook
*
* import { useCreate, useRecordContext } from 'react-admin';
*
* const LikeButton = () => {
* const record = useRecordContext();
* const like = { postId: record.id };
* const [create, { isPending, error }] = useCreate('likes', { data: like });
* if (error) { return <p>ERROR</p>; }
* return <button disabled={isPending} onClick={() => create()}>Like</button>;
* };
*
* @example // TypeScript
* const [create, { data }] = useCreate<Product>('products', { data: product });
* \-- data is Product
*/
export var useCreate = function (resource, params, options) {
if (params === void 0) { params = {}; }
if (options === void 0) { options = {}; }
var dataProvider = useDataProvider();
var queryClient = useQueryClient();
var _a = options.mutationMode, mutationMode = _a === void 0 ? 'pessimistic' : _a, getMutateWithMiddlewares = options.getMutateWithMiddlewares, mutationOptions = __rest(options, ["mutationMode", "getMutateWithMiddlewares"]);
var dataProviderCreate = useEvent(function (resource, params) {
return dataProvider.create(resource, params);
});
var _b = useMutationWithMutationMode(__assign({ resource: resource }, params), __assign(__assign({}, mutationOptions), { mutationKey: [resource, 'create', params], mutationMode: mutationMode, mutationFn: function (_a) {
var resource = _a.resource, params = __rest(_a, ["resource"]);
if (resource == null) {
throw new Error('useCreate mutation requires a resource');
}
if (params.data == null) {
throw new Error('useCreate mutation requires a non-empty data object');
}
return dataProviderCreate(resource, params);
}, updateCache: function (_a, _b, result) {
var _c;
var resource = _a.resource, params = __rest(_a, ["resource"]);
var mutationMode = _b.mutationMode;
var id = mutationMode === 'pessimistic'
? result === null || result === void 0 ? void 0 : result.id
: (_c = params.data) === null || _c === void 0 ? void 0 : _c.id;
if (!id) {
throw new Error('Invalid dataProvider response for create: missing id');
}
// 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.data));
queryClient.setQueryData([resource, 'getOne', { id: String(id), meta: params.meta }], function (record) { return (__assign(__assign({}, record), clonedData)); }, { updatedAt: updatedAt });
return clonedData;
}, getQueryKeys: function (_a, _b) {
var _c;
var resource = _a.resource, params = __rest(_a, ["resource"]);
var mutationMode = _b.mutationMode;
var queryKeys = [
[resource, 'getList'],
[resource, 'getInfiniteList'],
[resource, 'getMany'],
[resource, 'getManyReference'],
];
if (mutationMode !== 'pessimistic' && ((_c = params.data) === null || _c === void 0 ? void 0 : _c.id)) {
queryKeys.push([
resource,
'getOne',
{ id: String(params.data.id), meta: params.meta },
]);
}
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(dataProviderCreate.bind(dataProvider));
return function (args) {
// This is necessary to avoid breaking changes in useCreate:
// 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); };
}, onUndo: function (_a) {
var resource = _a.resource, data = _a.data, meta = _a.meta;
queryClient.removeQueries({
queryKey: [
resource,
'getOne',
{ id: String(data === null || data === void 0 ? void 0 : data.id), meta: meta },
],
exact: true,
});
}, onSettled: function (result, error, variables, context) {
// For creation, we always refetch after error or success:
context.snapshot.forEach(function (_a) {
var queryKey = _a[0];
queryClient.invalidateQueries({ queryKey: queryKey });
});
} })), mutate = _b[0], mutationResult = _b[1];
var create = 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 [create, mutationResult];
};
//# sourceMappingURL=useCreate.js.map