use-promise-factory generates a hook that provides a state and settled value of a Promise.
It is 451 bytes (268 gzipped).
Installation
npm install @jsxtools/use-promise-factory
Usage
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"
// the `settledValue` 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);
}