CSFrequency / react-firebase-hooks

React Hooks for Firebase.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Missing functions hook "useHttpsCallableFromUrl"

nipunasudha opened this issue · comments

I noticed the functions hook "useHttpsCallableFromUrl" is missing in the library. I'm not able to PR at the moment but here's a custom hook I use for that:

import {Functions, httpsCallableFromURL, HttpsCallableResult,} from 'firebase/functions';
import {useCallback, useState} from 'react';

export type HttpsCallableHook<
    RequestData = unknown,
    ResponseData = unknown
> = Readonly<
    [
        (
            data?: RequestData
        ) => Promise<HttpsCallableResult<ResponseData> | undefined>,
        boolean,
            Error | undefined
    ]
>;

export function useHttpsCallableFromUrl<RequestData = unknown, ResponseData = unknown>(
    functions: Functions,
    name: string
): HttpsCallableHook<RequestData, ResponseData> {
    const [error, setError] = useState<Error>();
    const [loading, setLoading] = useState<boolean>(false);

    const callCallable = useCallback(
        async (
            data?: RequestData
        ): Promise<HttpsCallableResult<ResponseData> | undefined> => {
            const callable = httpsCallableFromURL<RequestData, ResponseData>(
                functions,
                name
            );
            setLoading(true);
            setError(undefined);
            try {
                return await callable(data);
            } catch (err) {
                setError(err as Error);
            } finally {
                setLoading(false);
            }
        },
        [functions, name]
    );

    return [callCallable, loading, error] as const;
}