Getting Hooks.

Hook management solution.

Get Hooks

getHook(hooks, label)

Definition

The getHook function retrieves the list of functions associated with a specific label.

Usage

const hookList = getHook(hooks, "hook1");
  • Arguments:

    • hooks (Object): The hook manager object.
    • label (String): The label of the hook to retrieve.
  • Returns: An array of functions associated with the given label.

Real-World Example

You can use this function to get all hooks and perform some operations:

import { createBefter, hook, getHook } from "@farming-labs/befter";
const hooks = createBefter();

// Add some hooks
await hook(hooks, "beforeSave", () => console.log("Before saving"));
await hook(hooks, "afterSave", () => console.log("After saving"));

// Retrieve and call all hooks for 'beforeSave'
const beforeSaveHooks = await getHook(hooks, "beforeSave");

// You can use our callHook function to execute the hooks with a flexiblity of executing them in parallel or serially instead of calling them manually.
beforeSaveHooks.forEach((fn) => fn());

Get Hook With Index

getHookWithIndex(hooks, label, index)

Definition

The getHookWithIndex function retrieves a hook function from the list based on its index.

Usage

const hookFunction = await getHookWithIndex(hooks, "hook1", 0);
  • Arguments:

    • hooks (Object): The hook manager object.
    • label (String): The label of the hook to retrieve.
    • index (Number): The index of the hook function to retrieve.
  • Returns: The hook function at the specified index.

Real-World Example

You can retrieve a specific hook to update or replace it:

// Add hooks for form validation
const { currHook } = await hook(hooks, "formValidate", () =>
  console.log("Validating form"),
);

// Get the hook at index 0
const firstHook = await getHookWithIndex(hooks, "formValidate", 0);
console.log(firstHook); // Function: () => console.log('Validating form')