usePromise
settled したら再描画して、以降は値をしてくれる
reject のハンドルが面倒
ユースケースは幅広いと思う
値でも関数でも、両方入れられるのがポイント
code:usePromise.ts
import { useState, useEffect } from 'react';
type PromiseFunc<T> = () => Promise<T>;
export function usePromise<T, E = Error>(
promise: Promise<T> | PromiseFunc<T>
useEffect(() => {
if (typeof promise === 'function') {
promise = promise();
}
promise.then(value => {
// setValue function allows (prevState => nextState) as first arg. It should give (prevState => value)
if (typeof value === 'function') {
setValue(() => value);
} else {
setValue(value);
}
}, setError);
}, []);
}
これは useState を扱うライブラリ全般に言えることなのですが、 setValue する前に、valueが関数かどうかを判断するのがポイントです
関数の場合は prevState => nextState として扱われるので、関数がコールされて中身がセットされてしまいます