From 1963b6208a8b503273da892b4025058aafa798bd Mon Sep 17 00:00:00 2001 From: Madeorsk Date: Tue, 24 Sep 2024 23:04:11 +0200 Subject: [PATCH] Correctly memoize the promise from a function depending on deps when using useAsync. --- package.json | 2 +- src/Async.tsx | 14 +++++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 04ca60d..f9a79d6 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "version": "1.4.0", + "version": "1.4.1", "name": "@kernelui/core", "description": "Kernel UI Core.", "scripts": { diff --git a/src/Async.tsx b/src/Async.tsx index cea245c..950fc99 100644 --- a/src/Async.tsx +++ b/src/Async.tsx @@ -1,4 +1,4 @@ -import React, {useEffect, useState} from "react"; +import React, {useEffect, useMemo, useState} from "react"; /** * A type that can be returned by a promise or as is. @@ -41,10 +41,14 @@ export type PromiseFn = () => Promise; export function useAsync(promise: Promisable|PromiseFn, deps: any[] = []): [AsyncState, React.Dispatch] { // Get the actual promise from the function if there is one. - if ((promise as PromiseFn)?.call) - promise = (promise as PromiseFn)(); - else if (promise instanceof Promise) - promise = Promise.race([promise as Promise]); + promise = useMemo(() => { + if ((promise as PromiseFn)?.call) + return (promise as PromiseFn)(); + else if (promise instanceof Promise) + return Promise.race([promise as Promise]); + else + return promise; + }, deps); // The async state. const [state, setState] = useState>({