1.1.5 • Published 2 years ago

react-use-await v1.1.5

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

useAwait

React hook for resolving promises with Suspense support.

Fork of vigzmv's react-promise-suspense that has lot of wired bugs and is not longer under active development.

Inspired by fetch-suspense, but this one is not limited to fetch, useAwait works with any Promise.

version minified size minzipped size downloads

Install

yarn add react-use-await
# or using npm
npm install react-use-await --save

Example

Awaiting a fetch promise:

import useAwait from 'react-use-await';

const fetchJson = async (url, params) => {
  const response = await fetch(input);

  return await response.json();
};

const MyFetchingComponent = () => {
  // note: async function must be defined outside of component
  // you also can't use useCallback (reason https://github.com/facebook/react/issues/14563#issuecomment-453184356)
  const data = useAwait(fetchJson, [
    'https://pokeapi.co/api/v2/pokemon/ditto/',
    { method: 'GET' },
  ]);

  return <pre>{JSON.stringify(data, null, 2)}</pre>;
};

const App = () => {
  return (
    <React.Suspense fallback="Loading...">
      <MyFetchingComponent />
    </React.Suspense>
  );
};

Migration from react-promise-suspense

In most cases you don't need to do anything to migrate from react-promise-suspense to react-use-await (expect, surely imported package name replacement).

The only thing that changed in api without backward capability is that first argument of useAwait must persist between renders.

If first argument of useAwait is different (by reference) each of them will be called in infinite loop.

Migrations examples:

+  const fetchData = () => {...};
const MyFetchingComponent = () => {
-  const fetchData = React.useCallback(() => {...}, []);
  const date = useAwait(fetchData, )
}
+  const fetchData = () => {...};
const MyFetchingComponent = () => {
-  const fetchData = () => {...};
  const date = useAwait(fetchData, )
}
1.1.1

2 years ago

1.1.0

2 years ago

1.1.5

2 years ago

1.1.4

2 years ago

1.1.3

2 years ago

1.1.2

2 years ago

1.1.0-beta.2

2 years ago

1.1.0-beta.1

2 years ago

1.1.0-beta.0

2 years ago

1.1.0-beta.3

2 years ago

1.0.0

2 years ago

0.0.5

2 years ago

0.0.4-rc.1

2 years ago

0.0.4-rc

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago