-
Notifications
You must be signed in to change notification settings - Fork 2
/
UseAsyncValue.tsx
38 lines (33 loc) · 1.07 KB
/
UseAsyncValue.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Common
*/
import * as React from "react";
import { from } from "rxjs";
import { isPromiseLike } from "@itwin/core-react";
/**
* Custom hook for working with possibly async values.
* @public
*/
export function useAsyncValue<T>(value: T | PromiseLike<T>): T | undefined {
const [result, setResult] = React.useState(() => {
if (isPromiseLike(value)) {
return undefined;
}
return value;
});
React.useEffect(() => {
if (isPromiseLike(value)) {
const subscription = from(value).subscribe({
next: (resolvedValue) => setResult(resolvedValue),
});
return () => subscription.unsubscribe();
}
setResult(value);
return;
}, [value]);
return result;
}