-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: after import first time open will reload 2 times
fixes #31
- Loading branch information
Showing
3 changed files
with
58 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import { useEffect, useState } from 'react'; | ||
import { AsyncReturnType } from 'type-fest'; | ||
|
||
/** | ||
* Use value from service, especially constant value that never changes | ||
* This will only update once, won't listen on later update. | ||
* @param valuePromise A promise contain the value we want to use in React | ||
* @param defaultValue empty array or undefined, as initial value | ||
*/ | ||
export function usePromiseValue<T, DefaultValueType = T | undefined>( | ||
asyncValue: () => Promise<T>, | ||
defaultValue?: AsyncReturnType<typeof asyncValue>, | ||
dependency: unknown[] = [], | ||
): T | DefaultValueType { | ||
const [value, valueSetter] = useState<T | DefaultValueType>(defaultValue as T | DefaultValueType); | ||
// use initial value | ||
useEffect(() => { | ||
void (async () => { | ||
try { | ||
valueSetter(await asyncValue()); | ||
} catch (error) { | ||
console.error(error); | ||
if (defaultValue !== undefined) { | ||
valueSetter(defaultValue); | ||
} | ||
} | ||
})(); | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, dependency); | ||
|
||
return value; | ||
} |