Skip to content

Instantly share code, notes, and snippets.

@anoopt
Created March 7, 2023 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anoopt/3a527d74cbcb25eb334aef01721c2206 to your computer and use it in GitHub Desktop.
Save anoopt/3a527d74cbcb25eb334aef01721c2206 to your computer and use it in GitHub Desktop.
A custom react hook to call Azure functions
import * as React from 'react';
import { AadHttpClient, AadHttpClientFactory } from "@microsoft/sp-http";
import { APP_ID } from './constants';
export const useAzureFunctions = (aadHttpClientFactory: AadHttpClientFactory) => {
const clientRef = React.useRef<AadHttpClient>();
const getClient = React.useCallback(async () => {
if (!aadHttpClientFactory) {
return undefined;
}
const client = await aadHttpClientFactory.getClient(APP_ID);
clientRef.current = client;
}, [aadHttpClientFactory]);
const callAzureFunction = React.useCallback(
async (functionName: string, request: any, method: 'get' | 'post' = 'post') => {
try {
if (!clientRef.current) {
await getClient();
}
let requestHeaders: any = {};
requestHeaders['Content-Type'] = 'application/json';
let requestParams = '';
if (method === 'get' && request) {
// Add request params to URL query string
const params = new URLSearchParams(request).toString();
functionName += `?${params}`;
} else if (method === 'post') {
requestParams = JSON.stringify(request);
}
const response = await clientRef.current[method](
functionName,
AadHttpClient.configurations.v1,
{
headers: requestHeaders,
body: requestParams
}
);
console.log('response', response);
const result = await response.text();
console.log('Azure function result - ', result);
return result;
} catch (error) {
if (!DEBUG) {
console.error('Error:', error);
}
return undefined;
}
},
[getClient]
);
return { callAzureFunction };
};
/*
Example usage in a component
import { useAzureFunctions } from './hooks';
const { callAzureFunction } = useAzureFunctions(props.aadHttpClientFactory);
const AZURE_FUNCTION_UPDATE_PAGE = "http://localhost:7071/api/UpdatePage";
// call the Azure function and pass an object that the Azure function accepts
const response = await callAzureFunction(AZURE_FUNCTION_UPDATE_PAGE, { siteUrl, pageItemId, columnName, columnValue });
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment