JSPM

react-use-state-async

0.0.2
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1
  • Score
    100M100P100Q23352F
  • License MIT

A custom hook trigger call async function each dependencies changes. Support holding and updating for fetch data.

Package Exports

  • react-use-state-async

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-use-state-async) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

react-use-state-async

NPM JavaScript Style Guide

use-state-async

A custom hook trigger call async function each dependencies changes. Support holding and updating for fetch data.

Install

With npm

npm install --save react-use-state-async

With yarn

yarn add react-use-state-async

Usage

import * as React from "react";
import useStateAsync from "react-use-state-async";

export default function App() {
  const [url, setUrl] = React.useState("");
  const { isLoading, data, error, setData, fetch } = useStateAsync(() => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve("api data");
      }, 1000);
    });
  }, [url]);

  return (
    <div>
      <button onClick={() => setUrl("https://urlapi.com")}>Change url</button>
      <button onClick={() => fetch()}>Refetch api</button>
      <button onClick={() => setData("new data")}>Update data</button>
      {isLoading ? <p>Loading</p> : <p>Loaded</p>}
      {data && <p>{data}</p>}
      {error && <p>{error}</p>}
    </div>
  );
}

Props

useStateAsync(
  callback: () => any | async () => Promise<any>,
  dependencies: Array<any>
)

Exposed

parameter type description
isLoading boolean `true` if the callback function is running
data any the data is returned in callback function
error any the error is thrown in callback function
setData function update `data` state
fetch function trigger call callback function

License

MIT ©