# Actions framework

> \[!NOTE]
>
> For the Flex UI 2.x.x version of this content, see [Use UI Actions](/docs/flex/developer/ui/use-ui-actions).

Flex UI constantly emits asynchronous events and event payloads that describe how the user is interacting with the platform. With the Flex UI Actions Framework, you can manually invoke certain actions such as completing tasks, transferring tasks, holding a current call, and many more. Each action fires a before and after event, which allows you to handle your own logic before and after the action occurs. You can also replace the default behavior of an action with your own custom logic. As you develop Plugins, the Actions Framework allows you to describe how you want to interact with Flex UI or any CRM Data.

You can also view documentation for the [Actions Framework](https://assets.flex.twilio.com/docs/releases/flex-ui/1.33.0/ActionsManager.html) in the Flex UI 1.x.x API Reference.

## Register and invoke an action

[`Actions.registerAction`](https://assets.flex.twilio.com/docs/releases/flex-ui/1.33.0/ActionsManager.html#.registerAction) registers a named action and allows you to invoke the action later. The second argument is an [ActionFunction](https://assets.flex.twilio.com/docs/releases/flex-ui/1.33.0/ActionsManager.html#.ActionFunction) to be executed when the action is invoked. You can implement your logic in the ActionFunction.

```javascript
import { Actions } from "@twilio/flex-ui";

Actions.registerAction("AcceptTask", (payload) => {
   // Custom Logic Goes Here
});
```

[`Actions.invokeAction`](https://assets.flex.twilio.com/docs/releases/flex-ui/1.33.0/ActionsManager.html#.invokeAction) invokes actions that come out of the box with Flex, and the ones that you register. You can pass in an optional payload as a second parameter if the action needs any data when being invoked. When the named action is invoked, it fires a *before* and *after* event.

```javascript
import { Actions } from "@twilio/flex-ui";
Actions.invokeAction("AcceptTask", { sid: "WRXXXXXXXXXXXXXXXXX" });
```

## Replace an action

[Actions.replaceAction](https://assets.flex.twilio.com/docs/releases/flex-ui/1.33.0/ActionsManager.html#.replaceAction) replaces the default implementation of a named action with your own. The replaced action will be called with the same parameters as the original implementation, so you can add additional logic, then invoke the original action in your replacement function.

```javascript
import { Actions } from "@twilio/flex-ui";

Actions.replaceAction("AcceptTask", (payload, original) => {
    return new Promise((resolve, reject) => {
        alert("I have replaced this Action");
        resolve();
    }).then(() => original(payload));
});
```

## Add and remove event listeners

You can add and remove event listeners to events fired when an action is invoked. Every event name is the invoked action's name prefixed with either "before" or "after".

```javascript
import { Actions } from "@twilio/flex-ui";

Actions.addListener("beforeAcceptTask", (payload, cancelActionInvocation) => {
  // Implement logic before the AcceptTask action has been invoked
  if (someCondition) {
     // use this function to prevent the actual AcceptTask action from being invoked
     cancelActionInvocation();
  }
});

Actions.addListener("afterAcceptTask", (payload) => {
  // Implement logic after AcceptTask action has stopped executing
});

```

To remove a listener, you must provide the same function you used as an argument when registering the event. If you need to remove listeners, you should register your event listeners with a named function instead of an anonymous function.

### Registering event listeners with named functions

```javascript
import { Actions } from "@twilio/flex-ui";
const handleBeforeAcceptTask = (payload, cancelActionInvocation) => {
  // Implement logic before the AcceptTask action has been invoked
};

const handleAfterAcceptTask = (payload) => {
  // Implement logic after the AcceptTask action has stopped executing
};

// Register beforeAcceptTask and afterAcceptTask events

Actions.addListener("beforeAcceptTask", handleBeforeAcceptTask);
Actions.addListener("afterAcceptTask", handleAfterAcceptTask);
```

### Removing event listeners with named functions

You can remove event listeners by passing the name of the event with the original function used to register the event.

```javascript
Actions.removeListener("beforeAcceptTask", handleBeforeAcceptTask);
Actions.removeListener("afterAcceptTask", handleAfterAcceptTask);
```

## Supported events

For a list of all actions, visit the [Actions](https://assets.flex.twilio.com/docs/releases/flex-ui/1.33.0/Actions.html) section of the Flex UI 1.x.x API Reference. All event names take the name of the action, prefixed with before or after. Event names use camel case.

* **before\[eventName]** (for example `"beforeAcceptTask"`): These events are called when a named action is triggered, but before the action body is run. You can use this event type to cancel the action that's provided with event body.
* **after\[eventName]** (for example `"afterAcceptTask"`): These events are called after the action has stopped executing.

> \[!NOTE]
>
> The `afterLogout` event isn't supported. When a worker logs out, they return to the Flex login screen.

## Common use cases and examples

### Add an action after a task is accepted

Raises a JavaScript alert after an agent has clicked to accept any task.

```javascript
flex.Actions.addListener("afterAcceptTask", (payload) => alert("Triggered after event AcceptTask"));
```

### Ask for confirmation before accepting a task

Generates a prompt before task acceptance; prevent that action from running with an abort command if the user doesn't confirm.

```javascript
flex.Actions.addListener("beforeAcceptTask", (payload, abortFunction) => {
    alert("Triggered before event AcceptTask");
        if (!window.confirm("Are you sure you want to accept the task?")) {
            abortFunction();
        }
});
```

### Customize an existing action

Replaces the original action for `AcceptTask`. Injects custom logic to alert about the replacement, but executes the original action.

```javascript
flex.Actions.replaceAction("AcceptTask", (payload, original) => {
    return new Promise<void>((resolve, reject) => {
        alert("I have replaced this Action");
        resolve();
    }).then(() => original(payload));
});

```

### Register a custom action

Registers a custom action called `MyAction`, which makes a HTTP request. The example below also adds listener to the action `CompleteTask`, which invokes this custom action. This example could be used to update your CRM system.

```javascript
flex.Actions.registerAction("MyAction", (payload) => {
    return 
        fetch("https://my.server.backend.com/test")
        .then(response => {
            alert("Triggered MyAction with response " + JSON.stringify(response));
        })
        .catch(error => {
            console.log(error);
            throw error;
        });
});


flex.Actions.addListener("afterCompleteTask", (payload) => {return flex.Actions.invokeAction("MyAction")});
```

### Send a message after a task is completed

Sends a post-conversation message once the task is in a wrap-up state. For example, you could use this action to send a survey or notify a user that the agent closed the session.

```javascript
flex.Actions.replaceAction("WrapupTask", (payload, original) => {
    // Only alter chat tasks:
    if( payload.task.taskChannelUniqueName !== "chat" ) {
        original(payload);
    } else {
        return new Promise(function(resolve, reject) {
          // Send the message:
          flex.Actions.invokeAction("SendMessage", {
            body: 'Thanks for chatting. Your session is now closed.',
            channelSid: payload.task.attributes.channelSid
          }).then(response => {
            // Wait until the message is sent to wrap-up the task:
            resolve(original(payload));
        });

     });

   }

 });
```

## Next steps

* You can find the [full list of supported actions](https://assets.flex.twilio.com/docs/releases/flex-ui/1.33.0/Actions.html) or dive deeper into the [Action Manager interface](https://assets.flex.twilio.com/docs/releases/flex-ui/1.33.0/ActionsManager.html) using the Autogenerated Documentation.
* Learn more about the Notifications Framework to alert agents about changes in the Flex UI.
* Get started with [your first Flex Plugin](/docs/flex/quickstart/getting-started-plugin) and try customizing it using the Actions Framework.
