New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

react-use-state-async

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-use-state-async

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

  • 0.0.3
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

react-use-state-async

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

Demo

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";

const getSomethingApi = (id) => {
  return new Promise((res, rej) => {
    setTimeout(() => {
      if (id % 2 === 0) res({ id, fakeData: true });
      rej("cannot get data");
    }, 2000);
  });
};

export default function App() {
  const [id, setId] = React.useState(0);
  const { isLoading, setData, fetch, data, error } = useStateAsync(async () => {
    // do async action
    try {
      const res = await getSomethingApi(id);
      return res;
    } catch (e) {
      throw e;
    }
  }, [id]);

  return (
    <div>
      <button onClick={() => setId((previousId) => previousId + 1)}>
        Fetch data with increase Id
      </button>
      <button onClick={() => fetch()}>Refetch api</button>
      <button onClick={() => setData({ ...data, update: true })}>
        Update data
      </button>
      {isLoading ? <p>Loading</p> : <p>Loaded</p>}
      {data && <p>{JSON.stringify(data)}</p>}
      {error && <p>{JSON.stringify(error)}</p>}
    </div>
  );
}

Props

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

Exposed

parametertypedescription
isLoadingboolean`true` if the callback function is running
dataanythe data is returned in callback function
erroranythe error is thrown in callback function
setDatafunctionupdate `data` state
fetchfunctiontrigger call callback function

License

MIT ©

Keywords

FAQs

Package last updated on 23 Aug 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc