usepromises
TypeScript icon, indicating that this package has built-in type declarations

0.5.0 • Public • Published

usePromises

React and React Native hook to consume a Promise (similar to useEffect) with full TypeScript support

Installation

npm install --save usepromises

or

yarn add usepromises

Usage / Examples

usePromise

import { usePromise } from 'usepromises';
 
...
 
interface SampleResponse {
  slideshow: {
    title: string
  }
}
 
function Example() {
  const response = usePromise<SampleResponse>(async () => {
    const response = await fetch('https://httpbin.org/json');
    return response.json();
  }, []);
 
  return (
    <div>
      {response.isResolved && response.value.slideshow.title}
 
      {response.isRejected ? `Error: ${response.error}` : null}
    </div>
  );
};

useMountPromise

import { useMountPromise } from 'usepromises';
 
...
 
interface SampleResponse {
  slideshow: {
    title: string
  }
}
 
function Example() {
  const [response, setResponse] = useState<SampleResponse>();
  useMountPromise(async () => {
    const response = await fetch('https://httpbin.org/json');
    setResponse(response.json());
  });
 
  ...
};

useUnmountPromise

import { useUnmountPromise } from 'usepromises';
 
...
 
interface SampleResponse {
  slideshow: {
    title: string
  }
}
 
function Example() {
  useUnmountPromise(async () => {
    const response = await fetch('https://httpbin.org/json');
    console.warn('Server status code:', response.status);
  });
 
  ...
};

Package Sidebar

Install

npm i usepromises

Weekly Downloads

7

Version

0.5.0

License

MIT

Unpacked Size

26 kB

Total Files

17

Last publish

Collaborators

  • jerolimov