Returns a hook that provides a state and settled value of a Promise.
npm install @jsxtools/use-promise-factoryuse-promise-factory generates a [hook] that provides a state and settled value of a [Promise].
It is 451 bytes (268 gzipped).
``sh`
npm install @jsxtools/use-promise-factory
`js
import { useEffect, useState } from 'react';
import usePromiseFactory from '@jsxtools/use-promise-factory';
const usePromise = usePromiseFactory({ useEffect, useState });
function Component () {
// the state is "pending", "fulfilled", or "rejected"settledValue
// the is the fulfilled or rejected value
const [ state, settledValue ] = usePromise(async () => {
const response = await fetch(URL);
const json = await response.json();
return json;
});
return state === 'pending'
? 'Loading'
: JSON.stringify(settledValue);
}
``
[hook]: https://reactjs.org/docs/hooks-reference.html
[frontend]: https://github.com/jsxtools/frontend
[promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises