jerolimov / usepromises

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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 SampleData {
  slideshow: {
    title: string
  }
}

function Example() {
  const [data, setData] = useState<SampleData>();
  useMountPromise(async () => {
    const response = await fetch('https://httpbin.org/json');
    setData(await 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);
  });

  ...
};

About

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

License:MIT License


Languages

Language:TypeScript 93.9%Language:HTML 6.1%