What do the args for Gutenberg subpackage "hooks" function "doAction" mean?

All we need is an easy explanation of the problem, so here it is.

The package is supposed to mime WP’s own actions system:


I’ve installed it locally and loaded up all of its modules, unfortunately, I seriously don’t understand what the functionName and callback are in the case of addAction.

I tried messing with it quite a bit but no success. I thought functionName is the function I’m hooking to an action, for example:

var actions_api = createHooks();
function testFunction( a ) {
actions_api.addAction( 'testHook', 'global', 'testFunction', function( a ) {
}, 10 );
actions_api.doAction( 'testHook', 'super_arg' );

Returns the error The hook callback must be a function., while the code above seems stupid, I tried to mess with it a bit but no success.

What am I missing? In theory, there shouldn’t be a need for a callback for an action.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I suggest to take a look at the tests file to see different ways of using hooks.

They work similarly to PHP hooks, you can set several addAction and then one doAction with the name of the hook and other arguments.

The first argument of doAction has to be the action name. Then you can pass as many arguments as you want and those will pass to the addAction callback function:

const myFunction = ( arg1, arg2 ) => {
    console.log( arg1, arg2 ); // Should output 'Hello' 'Hola'

wp.hooks.addAction( 'action_name', 'function_name', myFunction );

wp.hooks.doAction( 'action_name', 'Hello', 'Hola' );

The first argument is the hook name. Several addAction (or addFilter) can hook into the given hook by its name and all will be executed when calling doAction (or applyFilters).
The second argument identifies the action or filter (addAction or addFilter). This is used, for example, if you want to remove one of the actions or filters. This is an adapted example taken from one of the tests:

const { addFilter, removeFilter, applyFilters } = wp.hooks;

function filterA(str) {
    return str + "A";

function filterB(str) {
    return str + "B";

function filterC(str) {
    return str + "C";

addFilter("test.filter", "my_callback_filter_a", filterA);
addFilter("test.filter", "my_callback_filter_b", filterB);
addFilter("test.filter", "my_callback_filter_c", filterC);

removeFilter("test.filter", "my_callback_filter_b");

console.log(applyFilters("test.filter", "test_")); // Should output test_AC

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply