Saving and deleting callbacks
When you are saving an entity you can attach different callbacks before and
after it gets saved: onPreSave
, onSaveSuccess
and onSaveFailure
.
These callbacks are defined at the collection level under the prop callbacks
.
This is useful if you need to add some logic or edit some fields before/after saving or deleting entities.
All callbacks are asynchronous.
note
You can stop the execution of these callbacks by throwing an Error
containing a string
and an error snackbar will be displayed.
import {
buildCollection,
buildEntityCallbacks,
EntityOnDeleteProps,
EntityOnSaveProps
} from "@camberi/firecms";
type Product = {
name: string;
uppercase_name: string;
}
const productCallbacks = buildEntityCallbacks({
onPreSave: ({
collection,
path,
entityId,
values,
status
}) => {
values.uppercase_name = values.name?.toUpperCase();
return values;
},
onSaveSuccess: (props: EntityOnSaveProps<Product>) => {
console.log("onSaveSuccess", props);
},
onSaveFailure: (props: EntityOnSaveProps<Product>) => {
console.log("onSaveFailure", props);
},
onPreDelete: ({
collection,
path,
entityId,
entity,
context
}: EntityOnDeleteProps<Product>
) => {
if (context.authController.user)
throw Error("Product deletion not allowed");
},
onDelete: (props: EntityOnDeleteProps<Product>) => {
console.log("onDelete", props);
},
});
const productCollection = buildCollection<Product>({
name: "Product",
path: "products",
properties: {
name: {
name: "Name",
validation: { required: true },
dataType: "string"
},
uppercase_name: {
name: "Uppercase Name",
dataType: "string",
disabled: true,
description: "This field gets updated with a preSave callback"
}
},
callbacks: productCallbacks
});
EntityOnSaveProps​
collection
: EntityCollection Resolved collection of the entitypath
: string Full path where this entity is being savedentityId
?: string Id of the entity or undefined if newvalues
: EntityValues Values being savedstatus
: EntityStatus New or existing entitycontext
: FireCMSContext Context of the app status
EntityOnDeleteProps​
collection
: EntityCollection Resolved collection of the entitypath
: string Full path where this entity is being savedentityId
?: string Id of the entity or undefined if newentity
: Entity Deleted entitycontext
: FireCMSContext Context of the app status