Factor out useEventEmitterState hook
This commit is contained in:
parent
cdf0d98c3f
commit
b3a28bde89
2 changed files with 21 additions and 7 deletions
|
@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
|
|||
limitations under the License.
|
||||
*/
|
||||
|
||||
import { useRef, useEffect } from "react";
|
||||
import { useRef, useEffect, useState, useCallback } from "react";
|
||||
import type { EventEmitter } from "events";
|
||||
|
||||
type Handler = (...args: any[]) => void;
|
||||
|
@ -48,3 +48,14 @@ export const useEventEmitter = (emitter: EventEmitter, eventName: string | symbo
|
|||
[eventName, emitter], // Re-run if eventName or emitter changes
|
||||
);
|
||||
};
|
||||
|
||||
type Mapper<T> = (...args: any[]) => T;
|
||||
|
||||
export const useEventEmitterState = <T>(emitter: EventEmitter, eventName: string | symbol, fn: Mapper<T>): T => {
|
||||
const [value, setValue] = useState<T>(fn());
|
||||
const handler = useCallback((...args: any[]) => {
|
||||
setValue(fn(...args));
|
||||
}, [fn]);
|
||||
useEventEmitter(emitter, eventName, handler);
|
||||
return value;
|
||||
};
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue