> For the complete documentation index, see [llms.txt](https://docs.corets.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.corets.io/hooks/use-action.md).

# useAction

Source code is hosted on [GitHub](https://github.com/corets/use-action)

{% tabs %}
{% tab title="yarn" %}

```bash
yarn add @corets/use-action
```

{% endtab %}

{% tab title="npm" %}

```
npm install --save @corets/use-action
```

{% endtab %}
{% endtabs %}

This library is built on top of this package:

{% content-ref url="/pages/-Mg7Kt8XOfsD4Np5cHGW" %}
[Async](/observables/async.md)
{% endcontent-ref %}

## useAction() <a href="#useaction" id="useaction"></a>

Takes a function or an instance of [`Async`](/observables/async.md) and turns it into an observable async operation that can be triggered manually any time in the future.

```typescript
import React, { useState } from "react"
import { Async } from "@corets/async"
import { useAction } from "@corets/use-action"

const sharedAction = new Async(async (argument: number) => `Global value is ${argument}`)

const Example = () => {
    const action = useAction(async (argument: number) => `Value is ${argument}`)
    const globalAction = useAction(sharedAction)
    
    const handleRun = () => action.run(Math.random())
    const handleCancel = () => action.cancel()
    
    if (action.isRunning()) {
        return <h1>Executing action...</h1>
    }
    
    if (action.isErrored()) {
        return <h1>There was an error :(</h1>
    }
    
    if (action.isCancelled()) {
        return <h1>Action has been cancelled</h1>
    }
    
    return (
        <div>
            Result: {action.getResult()}
            <button onClick={handleRun}>Run</button>
            <button onClick={handleCancel}>Cancel</button>
        </div>
    )
}
```

{% hint style="info" %}
Check out [Async](/observables/async.md) documentation for more details.
{% endhint %}
