Search.../

afterInsert( )

A hook that is triggered after an insert() operation.

Description

The afterInsert() hook runs when:

  • The insert() function is called.
  • An action is performed on a dataset that inserts a new item into the collection.
  • An item is inserted using the CMS.
  • An item is imported into the Sandbox or Live collection.

Return an object or a Promise that resolves to an object from the afterInsert() function. The returned object will be used as the result of the call to the insert() function instead of the actual item inserted into the collection. If returning a Promise, the object is used as the result, whether the Promise is fulfilled or rejected.

If the returned value is of the wrong type, the value is ignored.

A rejected Promise also calls the onFailure() hook if it has been registered.

Because the afterInsert hook is called after the insert() is executed, it cannot affect the item that is inserted into the collection. It can only affect the item returned by insert().

Syntax

function afterInsert(item: Object, context: HookContext): Promise<Object> | Object

afterInsert Parameters

NAME
TYPE
DESCRIPTION
item
Object

The item that was inserted.

context
HookContext

Contextual information about the hook.

Returns

The item to return to insert() instead of the inserted item. Returning a rejected promise will not block the operation, but will return a rejected promise to the caller as well as trigger the onFailure() hook.

Return Type:

Promise<Object>

 | 

Object

Was this helpful?

An afterInsert hook

Copy Code
1// In data.js
2
3export function myCollection_afterInsert(item, context) {
4 let hookContext = context; // see below
5
6 // some changes to the received item
7
8 return item;
9}
10
11/*
12 * hookContext:
13 *
14 * {
15 * "collectionName": "myCollection",
16 * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3",
17 * "userRole": "siteOwner"
18 * }
19 */
Change the item returned by insert() using an afterInsert hook

Copy Code
1// In data.js
2
3export function myCollection_afterInsert(item, context) {
4 let hookContext = context; // see below
5
6 //add a new property to the item being returned that aggregates the content from several fields into one
7 item.combinedSentence = `Customer: ${item.lastName}, ${item.firstName}: Purchases: ${item.purchases}, Item Returns: ${item.returns}`;
8
9 return item;
10}
11
12/*
13 * hookContext:
14 *
15 * {
16 * "collectionName": "myCollection",
17 * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3",
18 * "userRole": "siteOwner"
19 * }
20 */