trela
trela copied to clipboard
[Feature Update]: start API behavior / start APIの挙動
start APIの挙動について
start APIは、非同期処理を実行し結果をキャッシュして、実行したコンポーネントを描画更新する。
実行する非同期処理が実行中の場合は、read APIと同じように非同期処理を実行しないが、キャッシュが存在していても非同期処理を実行して、キャッシュを最新のものにしてからコンポーネントを描画更新する。そのため、コンポーネントのフィールドに書くと無限ループが発生していしまうため、フィールドで実行した場合にはエラーを投げる。
const SampleComponent = () => {
const { apis } = useTrela();
const ref = apis.anyAsyncFunc(); // 非同期処理の参照を取得
// ref.start(); <= このように書いてしまうとエラーを投げる
const startAsync = () => ref.start();
return (
<div>
<button onClick={startAsync}> 非同期処理を再実行する </button>
</div>
);
}
start APIの結果はread APIの返り値にも反映されるので、start APIの結果を受け取りたい場合はread APIを実行する必要がある。
const SampleComponent = () => {
const { apis } = useTrela();
const ref = apis.anyAsyncFunc(); // 非同期処理の参照を取得
const [ result, isLoading ] = ref.read(); // start APIの結果を受け取る事が出来る
const startAsync = () => ref.start();
return (
<div>
<button onClick={startAsync}> 非同期処理を再実行する </button>
</div>
);
}
start APIの型
type StartAPI = () => void
- start APIは、read APIと違って実行しても何も返さないので、結果などが欲しい場合は別のAPIと併用する必要がある。