Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add useCallableFunctionResponse #449

Merged
merged 5 commits into from
Sep 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/reference/README.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions docs/reference/modules/functions.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions docs/reference/modules/index.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 15 additions & 2 deletions docs/use.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
* [Show a single document](#show-a-single-document)
* [Show a list of data (collection)](#show-a-list-of-data-collection)
- [Cloud Functions](#cloud-functions)
* [Call a function](#call-a-function)
* [Call a function based on user interaction](#call-a-function-based-on-user-interaction)
* [Call a function on render](#call-a-function-on-render)
- [Realtime Database](#realtime-database)
* [Show an object](#show-an-object)
* [Show a list of data](#show-a-list-of-data)
Expand Down Expand Up @@ -304,7 +305,7 @@ function FavoriteAnimals() {

The following samples assume that `FirebaseAppProvider` and `FunctionsProvider` components exist higher up the component tree.

### Call a function
### Call a function based on user interaction

```jsx
function Calculator() {
Expand All @@ -327,6 +328,18 @@ function Calculator() {
}
```

### Call a function on render

If you want to call a function when a component renders, instead of in response to user interaction, you can use the `useCallableFunctionResponse` hook.

```jsx
function LikeCount({ videoId }) {
const { status, data: likeCount } = useCallableFunctionResponse('countVideoLikes', { data: { videoId: videoId } });
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about the name useCallableFunctionResponse? It's a little wordy because I wanted to emphasize that this would call the callable function and update with the response. Any suggestions to make it shorter/better?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wordy but I like that it's very explicit. SGTM


return <span>This video has {status === 'loading' ? '...' : likeCount} likes</span>;
}
```

## Realtime Database

The following samples assume that `FirebaseAppProvider` and `RealtimeDatabaseProvider` components exist higher up the component tree.
Expand Down
24 changes: 20 additions & 4 deletions example/withoutSuspense/Functions.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'firebase/storage';
import * as React from 'react';
import { useState } from 'react';
import { useFirebaseApp, FunctionsProvider, useFunctions } from 'reactfire';
import { useFirebaseApp, FunctionsProvider, useFunctions, useCallableFunctionResponse } from 'reactfire';
import { CardSection } from '../display/Card';
import { LoadingSpinner } from '../display/LoadingSpinner';
import { WideButton } from '../display/Button';
Expand All @@ -13,11 +13,12 @@ function UpperCaser() {
const [uppercasedText, setText] = useState<string>('');
const [isUppercasing, setIsUppercasing] = useState<boolean>(false);

const greetings = ['Hello World', 'yo', `what's up?`];
const textToUppercase = greetings[Math.floor(Math.random() * greetings.length)];

async function handleButtonClick() {
setIsUppercasing(true);

const greetings = ['Hello World', 'yo', `what's up?`];
const textToUppercase = greetings[Math.floor(Math.random() * greetings.length)];
const { data: capitalizedText } = await capitalizeTextRemoteFunction({ text: textToUppercase });
setText(capitalizedText);

Expand All @@ -27,11 +28,23 @@ function UpperCaser() {
return (
<>
<WideButton label="Uppercase some text" onClick={handleButtonClick} />
{isUppercasing ? <LoadingSpinner /> : <span>{uppercasedText}</span>}
{isUppercasing ? <LoadingSpinner /> : <span>{uppercasedText || `click the button to capitalize "${textToUppercase}"`}</span>}
</>
);
}

function UpperCaserOnRender() {
const greetings = ['Hello World', 'yo', `what's up?`];
const textToUppercase = greetings[Math.floor(Math.random() * greetings.length)];
const { status, data: uppercasedText } = useCallableFunctionResponse<{ text: string }, string>('capitalizeText', { data: { text: textToUppercase } });

if (status === 'loading') {
return <LoadingSpinner />;
}

return <span>{uppercasedText}</span>;
}

export function Functions() {
const app = useFirebaseApp();

Expand All @@ -40,6 +53,9 @@ export function Functions() {
<CardSection title="Call a cloud function">
<UpperCaser />
</CardSection>
<CardSection title="Call a function on render">
<UpperCaserOnRender />
</CardSection>
</FunctionsProvider>
);
}
28 changes: 28 additions & 0 deletions src/functions.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { httpsCallable as rxHttpsCallable } from 'rxfire/functions';
import { ReactFireOptions, useObservable, ObservableStatus } from './';
import { useFunctions } from '.';

import type { HttpsCallableOptions } from 'firebase/functions';

/**
* Calls a callable function.
*
* @param functionName - The name of the function to call
* @param options
*/
export function useCallableFunctionResponse<RequestData, ResponseData>(
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

☝️ this is where it is implemented

functionName: string,
options?: ReactFireOptions<ResponseData> & {
httpsCallableOptions?: HttpsCallableOptions;
data?: RequestData;
}
): ObservableStatus<ResponseData> {
const functions = useFunctions();
const observableId = `functions:callableResponse:${functionName}:${JSON.stringify(options?.data)}:${JSON.stringify(options?.httpsCallableOptions)}`;
const obsFactory = rxHttpsCallable<RequestData, ResponseData>(functions, functionName, options?.httpsCallableOptions);

//@ts-expect-error because RxFire doesn't make data optional. Remove when https://github.com/FirebaseExtended/rxfire/pull/34 is released.
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const observable$ = obsFactory(options?.data);

return useObservable(observableId, observable$, options);
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export * from './auth';
export * from './database';
export * from './firebaseApp';
export * from './firestore';
export * from './functions';
export * from './performance';
export * from './remote-config';
export * from './storage';
Expand Down
18 changes: 16 additions & 2 deletions test/functions.test.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { initializeApp } from 'firebase/app';
import { getFunctions, connectFunctionsEmulator, httpsCallable } from 'firebase/functions';
import { FunctionComponent } from 'react';
import { FirebaseAppProvider, FunctionsProvider, useFunctions } from '..';
import { FirebaseAppProvider, FunctionsProvider, useFunctions, useCallableFunctionResponse } from '..';
import { baseConfig } from './appConfig';
import { renderHook } from '@testing-library/react-hooks';
import { randomString } from './test-utils';
import * as React from 'react';

describe('Functions', () => {
Expand All @@ -25,12 +26,25 @@ describe('Functions', () => {
expect(functionsInstance).toBeDefined();

// `capitalizeText` function is in `functions/index.js`
const capitalizeTextRemoteFunction = httpsCallable(functionsInstance, 'capitalizeText');
const capitalizeTextRemoteFunction = httpsCallable<{ text: string }, string>(functionsInstance, 'capitalizeText');
const testText = 'Hello World';

const { data: capitalizedText } = await capitalizeTextRemoteFunction({ text: testText });

expect(capitalizedText).toEqual(testText.toUpperCase());
});
});

describe('useCallableFunctionResponse', () => {
it('calls a function on render', async () => {
const testText = randomString();
const { result, waitFor } = renderHook(() => useCallableFunctionResponse<{ text: string }, string>('capitalizeText', { data: { text: testText } }), {
wrapper: Provider,
});

await waitFor(() => result.current.status === 'success');

expect(result.current.data).toEqual(testText.toUpperCase());
});
});
});