Created
September 24, 2024 05:51
-
-
Save Phryxia/2b605d237295b73f4ed9e92c474bad45 to your computer and use it in GitHub Desktop.
Listen for promises and give the last promise value as react state
This file contains hidden or 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
| import { useLayoutEffect, useRef, useState } from 'react' | |
| export function usePromise<T>(promise: Promise<T>) { | |
| const [isLoading, setIsLoading] = useState(true) | |
| const [value, setValue] = useState<T>() | |
| const valueVersion = useRef(0) | |
| useLayoutEffect(() => { | |
| const valueOnClosure = ++valueVersion.current | |
| promise.then(newValue => { | |
| if (valueOnClosure < valueVersion.current) return | |
| setValue(newValue) | |
| setIsLoading(false) | |
| }) | |
| setIsLoading(true) | |
| }, [promise]) | |
| return { value, isLoading } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment