Last active
January 24, 2025 15:54
-
-
Save vasylnahuliak/a701840a8948a4dbfeafc2001f1941be to your computer and use it in GitHub Desktop.
useRef with Promise
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 { useRef, MutableRefObject } from 'react'; | |
interface PromiseRef<T, E> { | |
promise: Promise<T>; | |
resolve: (value: T) => void; | |
reject: (reason: E) => void; | |
} | |
type UsePromiseRefReturn<T, E> = [ | |
MutableRefObject<PromiseRef<T, E> | null>, | |
() => void, | |
]; | |
export const usePromiseRef = <T, E>(): UsePromiseRefReturn<T, E> => { | |
const promiseRef = useRef<PromiseRef<T, E> | null>(null); | |
const createPromise = () => { | |
let resolveCallback: (value: T) => void; | |
let rejectCallback: (reason: E) => void; | |
const promise = new Promise<T>((resolve, reject) => { | |
resolveCallback = resolve; | |
rejectCallback = reject; | |
}); | |
promiseRef.current = { | |
promise, | |
resolve: resolveCallback!, | |
reject: rejectCallback!, | |
}; | |
}; | |
return [promiseRef, createPromise]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example of using usePromiseRef with WebView onMessage