Add useNuiEventCallback hook (#173)

* Add useNuiEventCallback hook
This commit is contained in:
J Francisco Rader authored and GitHub committed 2021-03-19 11:54:26 -03:00
1 parent 769f5a3d21
commit 97c308f550
3 files changed
+136 -8

No files matched your search

@@ -0,0 +1,104 @@
import { FetchData } from '@sentry/tracing/dist/browser/request';
import { useCallback, useEffect, useRef, useState } from 'react';
import Nui, { IAbortableFetch } from '../utils/Nui';
import { eventNameFactory } from '../utils/nuiUtils';
import { useNuiEvent } from './useNuiEvent';
type UseNuiEventCallbackResponse<I, R> = [
(d?: I) => void,
{ loading: boolean; error: any; response: R },
];
export const useNuiEventCallback = <I = FetchData, R = FetchData>(
app: string,
method: string,
handler?: (res: R) => void,
errHandler?: Function,
): UseNuiEventCallbackResponse<I, R> => {
const fetchRef = useRef<IAbortableFetch>();
const timeoutRef = useRef<NodeJS.Timeout>();
// These are Refs to avoid re renders.
// We dont care if "app" and "method" arguments change.
const eventNameRef = useRef<string>(eventNameFactory(app, method));
const methodNameRef = useRef<string>(method);
const appNameRef = useRef<string>(app);
const [timedOut, setTimedOut] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<any>(null);
const [response, setResponse] = useState<R>(null);
const onSuccess = useCallback(
(data: R) => {
if (!loading) {
return;
}
// If we receive eventNameSuccess event, clear timeout
timeoutRef.current && clearTimeout(timeoutRef.current);
// If already timed out, don't do shit :)
if (timedOut) {
return;
}
// Set new state after success event received
setResponse(data);
setError(null);
setLoading(false);
handler?.(data);
},
[handler, timedOut, loading],
);
const onError = useCallback(
(err: any) => {
if (!loading) {
return;
}
// If we receive eventNameSuccess event, clear timeout
timeoutRef.current && clearTimeout(timeoutRef.current);
// If already timed out, don't do shit :)
if (timedOut) {
return;
}
// Set new state after error event received
setError(err);
setResponse(null);
setLoading(false);
errHandler?.(err);
},
[errHandler, timedOut, loading],
);
// React to loading change and starting timeout timer.
useEffect(() => {
if (loading && !timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = setTimeout(() => {
setTimedOut(true);
onError(
new Error(`${eventNameRef.current} NUI Event Callback timed out after 10000 seconds`),
);
fetchRef.current && fetchRef.current.abort();
timeoutRef.current = undefined;
fetchRef.current = undefined;
}, 10000);
}
}, [loading, onError]);
// Handle the success and error events for this method
useNuiEvent(appNameRef.current, `${methodNameRef.current}Success`, onSuccess);
useNuiEvent(appNameRef.current, `${methodNameRef.current}Error`, onError);
// Only fetch if we are not loading/waiting the events.
const fetch = useCallback((data?: I) => {
setLoading((curr) => {
if (!curr) {
fetchRef.current = Nui.sendAbortable(methodNameRef.current, data);
return true;
}
return curr;
});
}, []);
return [fetch, { loading, response, error }];
};
+29 -6
View File
@@ -1,13 +1,36 @@
// eslint-disable-next-line
export default {
async send(event: any, data = {}) {
/* eslint-disable no-unreachable */
return fetch(`https://new-phone-who-dis/${event}`, {
export interface IAbortableFetch {
abort: () => void;
promise: Promise<Response>;
}
function abortableFetch(request, opts): IAbortableFetch {
const controller = new AbortController();
const signal = controller.signal;
return {
abort: () => controller.abort(),
promise: fetch(request, { ...opts, signal }),
};
}
function getParams(event, data): [RequestInfo, RequestInit] {
return [
`https://new-phone-who-dis/${event}`,
{
method: 'post',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify(data),
});
},
];
}
export default {
async send(event: any, data = {}) {
return fetch(...getParams(event, data));
},
sendAbortable(event: any, data = {}): IAbortableFetch {
return abortableFetch(...getParams(event, data));
},
};
+3 -2
View File
@@ -1,2 +1,3 @@
export const eventNameFactory = (app: any, method: any) => `${app}:${method}`;
export const eventNameMethod = (name: any) => name.split(':')[1] || null;
export const eventNameFactory = (app: string, method: string) => `${app}:${method}`;
export const eventNameMethod = (name: string) => name.split(':')[1] || null;