@dioklecijan/use-async
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

@dioklecijan/use-async

a React hook for executing async functions

NPM JavaScript Style Guide

Install

npm install --save @dioklecijan/use-async

Usage

import * as React from 'react'
import { useAsync } from '@dioklecijan/use-async'

// async function to execute
const getCurrentRate = async (base:string) => {
  const url = `https://api.ratesapi.io/api/latest?base=${base}`;
  const res = await fetch(url);
  return res.json();
}

// component with useAsync hook
const Example = () => {
  const fx = useAsync(getCurrentRate, true, "EUR", "GBP,USD");
  return (
    <div>
    <div>
      <h1>European Central Bank exchange rates</h1>
      <button onClick={() => fx.execute("EUR")}>Get all rates</button>
      {fx.state.error && <div>Error: {fx.state.error.message}</div>}
      {fx.state.pending && <div>Fetching rates...</div>}
      {fx.state.value && <pre>{JSON.stringify(fx.state.value, null, 2)}</pre>}
    </div>
  )
}

See ./example/src/App.js for a complete example.

License

MIT © dioklecijan


This hook is created using create-react-hook.

Versions

Current Tags

VersionDownloads (Last 7 Days)Tag
1.0.026latest

Version History

VersionDownloads (Last 7 Days)Published
1.0.026

Package Sidebar

Install

npm i @dioklecijan/use-async

Weekly Downloads

26

Version

1.0.0

License

MIT

Unpacked Size

623 kB

Total Files

26

Last publish

Collaborators

  • dioklecijan