useAction

React hook for imperative async operations.

Source code is hosted on GitHub

yarn add @corets/use-action

This library is built on top of this package:

useAction()

Takes a function or an instance of Async and turns it into an observable async operation that can be triggered manually any time in the future.

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>
    )
}

Check out Async documentation for more details.

Last updated