-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseNuiEvent.ts
More file actions
32 lines (27 loc) · 1.1 KB
/
useNuiEvent.ts
File metadata and controls
32 lines (27 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { useEffect, useRef } from "react";
/**
* Hook สำหรับรับ Event จาก FiveM NUI ผ่าน window.message
* @param action ชื่อ action ที่ต้องการรับ (ต้องตรงกับ SendNUIMessage)
* @param handler ฟังก์ชัน callback เมื่อได้รับ event
*/
export const useNuiEvent = <T = any>(
action: string,
handler: (data: T) => void
) => {
const savedHandler = useRef<(data: T) => void>();
// จดจำ handler ล่าสุดเสมอ
useEffect(() => {
savedHandler.current = handler;
}, [handler]);
useEffect(() => {
const eventListener = (event: MessageEvent) => {
const { action: eventAction, data } = event.data || {};
// ถ้า action ตรงกัน เรียก handler
if (savedHandler.current && eventAction === action) {
savedHandler.current(data);
}
};
window.addEventListener("message", eventListener);
return () => window.removeEventListener("message", eventListener);
}, [action]);
};