4.1.0 • Published 4 years ago

@bytesoftio/use-async v4.1.0

Weekly downloads
13
License
MIT
Repository
github
Last release
4 years ago

@bytesoftio/use-async

Installation

yarn add @bytesoftio/use-async or npm install @bytesoftio/use-async

Table of contents

Description

A convenient hook to deal with async operations inside React components.

useAsync

Function useAsync takes any other function that returns anything that can be awaited and returns its result as soon as the promise resolves. You also get some useful things like a loading indicator, the possible error that might have been thrown / or occurred through rejection and a reload function to rerun the async procedure. Async action can also be canceled with cancel or resolved directly using resolve.

import React from "react"
import { useAsync } from "@bytesoftio/use-async"

const fetchCommodityPrice = (commodity: string) => {
  return new Promise<string>((resolve) => {
    setTimeout(() => resolve(`${commodity}: 1000$`), 3000)
  })
}

const Component = () => {
  const handle = useAsync(() => fetchCommodityPrice("gold"))

  if (handle.loading) {
    return <span>Loading...</span>
  }

  if (handle.error) {
    return <span>There was an error :(</span>
  }

  return (
    <div>
      <span>{handle.result}</span>
      {/* reload commodity price */}
      <button onClick={() => handle.reload()}>reload</button>
      {/* fetch price for another commodity by replacing */}
      {/* the async action with a slightly different one */}
      <button onClick={() => handle.reload(() => fetchCommodityPrice("silver"))}>fetch price for silver</button>
    </div>
  )
}
4.1.0

4 years ago

4.0.0

4 years ago

3.0.0

4 years ago

2.1.0

4 years ago

2.0.0

4 years ago

1.2.2

4 years ago

1.2.1

4 years ago

1.2.0

4 years ago

1.1.1

4 years ago

1.1.0

4 years ago

1.0.0

4 years ago