From 97c308f55023b8f452a0dc4a49bc84244e50b024 Mon Sep 17 00:00:00 2001 From: J Francisco Rader Date: Fri, 19 Mar 2021 11:54:26 -0300 Subject: [PATCH] Add useNuiEventCallback hook (#173) * Add useNuiEventCallback hook --- .../nui-events/hooks/useNuiEventCallback.ts | 104 ++++++++++++++++++ phone/src/os/nui-events/utils/Nui.ts | 35 +++++- phone/src/os/nui-events/utils/nuiUtils.ts | 5 +- 3 files changed, 136 insertions(+), 8 deletions(-) create mode 100644 phone/src/os/nui-events/hooks/useNuiEventCallback.ts diff --git a/phone/src/os/nui-events/hooks/useNuiEventCallback.ts b/phone/src/os/nui-events/hooks/useNuiEventCallback.ts new file mode 100644 index 0000000..21f5660 --- /dev/null +++ b/phone/src/os/nui-events/hooks/useNuiEventCallback.ts @@ -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 = [ + (d?: I) => void, + { loading: boolean; error: any; response: R }, +]; + +export const useNuiEventCallback = ( + app: string, + method: string, + handler?: (res: R) => void, + errHandler?: Function, +): UseNuiEventCallbackResponse => { + const fetchRef = useRef(); + const timeoutRef = useRef(); + + // These are Refs to avoid re renders. + // We dont care if "app" and "method" arguments change. + const eventNameRef = useRef(eventNameFactory(app, method)); + const methodNameRef = useRef(method); + const appNameRef = useRef(app); + + const [timedOut, setTimedOut] = useState(false); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + const [response, setResponse] = useState(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 }]; +}; diff --git a/phone/src/os/nui-events/utils/Nui.ts b/phone/src/os/nui-events/utils/Nui.ts index 2597040..bc9bfca 100644 --- a/phone/src/os/nui-events/utils/Nui.ts +++ b/phone/src/os/nui-events/utils/Nui.ts @@ -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; +} + +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)); }, }; diff --git a/phone/src/os/nui-events/utils/nuiUtils.ts b/phone/src/os/nui-events/utils/nuiUtils.ts index 3ddebbd..a04fa9c 100644 --- a/phone/src/os/nui-events/utils/nuiUtils.ts +++ b/phone/src/os/nui-events/utils/nuiUtils.ts @@ -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;