LogoLogo
  • Home
  • Services
    • Fiber
    • Accessor
    • Schema
    • Form
    • Translator
  • Components
    • <Router/>
    • <Memo />
  • Observables
    • Async
    • Value
    • Store
    • List
    • Local Storage Value
    • Local Storage Store
    • Local Storage List
  • Hooks
    • useAsync
    • useAffect
    • useStream
    • useAction
    • useDebounce
    • useThrottle
    • usePrevious
    • useIdle
    • useValue
    • useList
    • useStore
    • useForm
    • useFormBinder
    • useTranslator
    • useQuery
  • Helpers
    • Tag
    • Input Helpers
    • Promise Helpers
    • Save Helpers
    • Pagination Helpers
    • Clipboard Helpers
    • Calendar Helpers
    • Local Storage Helpers
Powered by GitBook
On this page

Was this helpful?

  1. Hooks

useAction

React hook for imperative async operations.

PrevioususeStreamNextuseDebounce

Last updated 3 years ago

Was this helpful?

Source code is hosted on

yarn add @corets/use-action
npm install --save @corets/use-action

This library is built on top of this package:

useAction()

Takes a function or an instance of 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 documentation for more details.

GitHub
Async
Async
Async