mirror of
https://github.com/darksaid98/new-phone-who-dis.git
synced 2026-12-03 06:28:51 +00:00
enhance(phone): useNuiEvent types and integrated DebugLogger
This commit is contained in:
1 parent
6bb534231b
commit
8a2f281790
1 file changed
+26
-7
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { MutableRefObject, useEffect, useRef } from 'react';
|
||||
import { eventNameFactory } from '../utils/nuiUtils';
|
||||
import DebugLog from '../../debug/LogDebugEvents';
|
||||
|
||||
interface IOptions {
|
||||
capture?: boolean;
|
||||
@@ -7,30 +8,48 @@ interface IOptions {
|
||||
once?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A hook that manage events listeners for receiving data from the NUI
|
||||
* @param app The app name in which this hoook is used
|
||||
* @param method The specific `method` field that should be listened for.
|
||||
* @param handler The callback function that will handle data relayed by this hook
|
||||
* @param options Any options to pass to the addEventListener
|
||||
**/
|
||||
|
||||
export const useNuiEvent = (
|
||||
app: any,
|
||||
method: any,
|
||||
handler: any,
|
||||
app: string,
|
||||
method: string,
|
||||
handler: Function,
|
||||
options: IOptions = {}
|
||||
) => {
|
||||
const savedHandler: any = useRef();
|
||||
const savedHandler: MutableRefObject<any> = useRef();
|
||||
// Destructure passed options
|
||||
const { capture, passive, once } = options;
|
||||
|
||||
// When handler value changes set mutable ref to handler val
|
||||
useEffect(() => {
|
||||
savedHandler.current = handler;
|
||||
}, [handler]);
|
||||
|
||||
// Will run every rerender
|
||||
useEffect(() => {
|
||||
const eventName = eventNameFactory(app, method);
|
||||
const eventListener = (event: any) => {
|
||||
const eventListener = (event) => {
|
||||
if (savedHandler.current && savedHandler.current.call) {
|
||||
const { data } = event;
|
||||
console.log(eventName, data);
|
||||
DebugLog({
|
||||
action: `NUI Data Received (${eventName})`,
|
||||
data: event.data,
|
||||
level: 1,
|
||||
});
|
||||
savedHandler.current(data);
|
||||
}
|
||||
};
|
||||
// Why are destructing then restructuring option data?
|
||||
const opts = { capture, passive, once };
|
||||
|
||||
window.addEventListener(eventName, eventListener, opts);
|
||||
// Remove Event Listener on component cleanup
|
||||
return () => window.removeEventListener(eventName, eventListener, opts);
|
||||
}, [app, method, capture, passive, once]);
|
||||
};
|
||||
Reference in new issue
Block a user