Search.../

beforeQuery( )

A hook that is triggered before a find() operation.

Description

The beforeQuery() hook runs when:

  • The find function is called.
  • An action is performed on a dataset that retrieves items from the collection.
  • The collection is viewed in the Data Manager.
  • An item is exported from the collection.

The hook also runs when an action is performed on a dataset that retrieves items from the collection that the dataset is connected to.

Return a query or a Promise that resolves to a query from the beforeQuery() function. The returned query will be used as the query for the find operation.

Often, you will modify the query that is received in the query parameter by calling one or more WixDataQuery functions.

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

A rejected Promise blocks the call to find() and also calls the onFailure() hook if it has been registered.

Because the beforeQuery() hook is called before find() is executed, it can affect the query that is used to retrieve items or block the find().

Syntax

function beforeQuery(query: WixDataQuery, context: HookContext): Promise<WixDataQuery> | WixDataQuery

beforeQuery Parameters

NAME
TYPE
DESCRIPTION
query

WixDataQuery

The original query as specified by the caller.

context

HookContext

Contextual information about the hook.

Returns

The query to use instead of the original query specified by the caller. Returning a rejected promise will block the operation and will return a rejected promise to the operation caller as well as trigger the onFailure() hook.

Return Type:

Was this helpful?

A beforeQuery hook

Code Example

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

Code Example

Copy Code
1// In data.js
2
3export function myCollection_beforeQuery(query, context) {
4 let hookContext = context; // see below
5
6 // some change to the received query
7 let newQuery = query.eq("status", "active");
8
9 return newQuery;
10}
11
12/*
13 * hookContext:
14 *
15 * {
16 * "collectionName": "myCollection",
17 * "userId": "f45jf8d2-grkj-2opd-4ovk-9rfj4wo5tvj3",
18 * "userRole": "siteOwner"
19 * }
20 */