// Handler for Networks API
const runNetworksApi = async () => {
showLoader(true);
try {
const result = await althermaService.getAvailableNetworks();
if ("error" in result && result.error) {
setApiResponse(`Error: ${JSON.stringify(result.error)}`);
} else {
setApiResponse(`Success: ${JSON.stringify(result.data)}`);
}
} catch (error: any) {
setApiResponse(`Exception: ${error.message}`);
} finally {
showLoader(false);
}
};
// Handler for Settings API
const runSettingsApi = async (shouldReset: boolean = false) => {
showLoader(true);
try {
// Define your settings here. Replace with actual settings as needed.
const settings: iWLANSettings = {
ssid: !shouldReset ? "Hathway_Ashish2.4G" : "",
security: !shouldReset ? "WPA_WPA2_MIXED" : "",
key: !shouldReset ? "8296494290" : "",
};
const result = await althermaService.configureWifiConnection(settings);
if ("error" in result && result.error) {
setApiResponse(`Error: ${JSON.stringify(result.error)}`);
} else {
setApiResponse(`Success: ${JSON.stringify(result.data)}`);
}
} catch (error: any) {
setApiResponse(`Exception: ${error.message}`);
} finally {
showLoader(false);
}
};
// Handler for Info API
const runInfoApi = async () => {
showLoader(true);
try {
const result = await althermaService.getWlanInfo();
if ("error" in result && result.error) {
setApiResponse(`Error: ${JSON.stringify(result.error)}`);
} else {
setApiResponse(`Success: ${JSON.stringify(result.data)}`);
}
} catch (error: any) {
setApiResponse(`Exception: ${error.message}`);
} finally {
showLoader(false);
}
};
const navigateBack = () => {
showLoader(false);
const filteredRoutes = routes.filter((item) => {
return item.name === "ConfigureThermostatScreen";
});
if (filteredRoutes.length > 0) {
navigation.pop(1);
}
navigation.goBack();
};
const reboot = async () => {
showLoader(true);
/**
* Check if still connected to thermostat hotspot
* If yes call reboot api, we won't check for status because irrespective of the result we need to take user back
* If not then just navigate back
*/
const isConnectedToMiniSplitSSID =
await isConnectedToSSIDPrefix(ALTHERMA_SSID);
if (isConnectedToMiniSplitSSID.isConnected) {
await runSettingsApi();
await timeout(MINI_SPLIT_CONNECT_TIMEOUT);
navigateBack();
} else {
navigateBack();
}
};
const onDismissAlert = () => {
// setIsFetchingWifiList(false);
setAlertStatus({
isVisible: false,
buttonAlignment: alertStatus.buttonAlignment,
title: alertStatus.title,
message: alertStatus.message,
positiveBtnLabel: alertStatus.positiveBtnLabel,
negativeBtnLabel: alertStatus.negativeBtnLabel,
onPress: null,
onCancel: null,
});
};
return (
<Background style={styles.root}>
<View style={styles.container}>
<DaikinLiteWifiAlert
ssidPrefix={ALTHERMA_SSID}
navigation={navigation}
/>
<Alert
visible={alertStatus.isVisible}
title={alertStatus.title}
buttonAlignment={alertStatus.buttonAlignment}
description={alertStatus.message}
positiveButtonTitle={
alertStatus.positiveBtnLabel ||
translate(translationKeys.alert.okayButtonLabel)
}
negativeButtonTitle={alertStatus.negativeBtnLabel}
alternateButtonTitle={alertStatus.alternativeBtnLabel}
onPress={alertStatus.onPress || onDismissAlert}
onCancel={alertStatus.onCancel || onDismissAlert}
onPressAlternate={alertStatus.onPressAlternate || onDismissAlert}
/>
<Label
text="Click on the buttons below to check the Altherma APIs"
style={styles.description}
/>
<Button
title="Run Scan API"
style={[styles.scanButton]}
onPress={runScanApi}
/>
<Button
title="Run Networks API"
style={[styles.scanButton]}
onPress={runNetworksApi}
/>
<Button
title="Run Settings API"
style={[styles.scanButton]}
onPress={runSettingsApi}
/>
<Button
title="Run Info API"
style={[styles.scanButton]}
onPress={runInfoApi}
/>
<View style={styles.responseWrapper}>
<ScrollView
style={styles.responseContainer}
contentContainerStyle={{flexGrow: 1}}
>
<Text style={styles.responseText}>
{apiResponse || "API response will appear here"}
</Text>
</ScrollView>
</View>
</View>
</Background>
);
}; this is my code optimise my api calls
To optimize your API calls and reduce code duplication in your React Native component, we can create a generic helper function that handles the common logic for all your API calls. This will make your code cleaner, more maintainable, and easier to read.
Here's how you can refactor your code:
Create a Generic API Call Handler
First, define a handleApiCall function that encapsulates the common logic for making API calls, handling success and error responses, and updating the loader and response state.
Update your handler functions to use the handleApiCall function. This removes the repeated code in each function and centralizes the API call logic.
typescript
// Handler for Scan API
const runScanApi = () => handleApiCall(() => althermaService.scanWifiNetworks());
// Handler for Networks API
const runNetworksApi = () => handleApiCall(() => althermaService.getAvailableNetworks());
// Handler for Settings API
const runSettingsApi = (settings: iWLANSettings) =>
handleApiCall(() => althermaService.configureWifiConnection(settings));
// Handler for Info API
const runInfoApi = () => handleApiCall(() => althermaService.getWlanInfo());
For runSettingsApi, you can pass the settings object as a parameter, allowing you to customize it when calling the function.
Refactor the Reboot Function
Ensure that the reboot function properly handles the loader state and appropriately calls the runSettingsApi with empty settings to reset the device.
typescript
const reboot = async () => {
showLoader(true);
try {
// Check if still connected to thermostat hotspot
const isConnectedToMiniSplitSSID = await isConnectedToSSIDPrefix(ALTHERMA_SSID);
if (isConnectedToMiniSplitSSID.isConnected) {
// Reset the settings by calling runSettingsApi with empty settings
const emptySettings: iWLANSettings = {
ssid: '',
security: '',
key: '',
};
await runSettingsApi(emptySettings);
await timeout(MINI_SPLIT_CONNECT_TIMEOUT);
}
} catch (error: any) {
setApiResponse(`Exception in reboot: ${error.message}`);
} finally {
showLoader(false);
navigateBack();
}
};
Optimize the Alert Dismiss Function
Update the onDismissAlert function to only change the isVisible attribute and reset the onPress and onCancel handlers, making use of the previous state.
To prevent unnecessary re-renders and improve performance, wrap your handler functions with useCallback. This memoizes the functions and ensures they are only recreated when their dependencies change.
Ensure that your JSX uses the new handler functions correctly. Pass any necessary parameters when calling runSettingsApi.
jsx
<Label
text="Click on the buttons below to check the Altherma APIs"
style={styles.description}
/>
<Button
title="Run Scan API"
style={styles.scanButton}
onPress={runScanApi}
/>
<Button
title="Run Networks API"
style={styles.scanButton}
onPress={runNetworksApi}
/>
<Button
title="Run Settings API"
style={styles.scanButton}
onPress={() => {
// Define your settings here or fetch them from state
const settings: iWLANSettings = {
ssid: 'Hathway_Ashish2.4G',
security: 'WPA_WPA2_MIXED',
key: '8296494290',
};
runSettingsApi(settings);
}}
/>
<Button
title="Run Info API"
style={styles.scanButton}
onPress={runInfoApi}
/>
Ensure Proper State Management
Make sure that your state updates and dependencies are properly managed to prevent any issues with stale data or unnecessary re-renders.
By applying these optimizations, your API call functions become more concise and maintainable, and your component's performance should improve due to reduced re-renders and memoized functions.
Here's the optimized code:
typescript
By centralizing the API call logic and reducing code repetition, you've optimized your API calls and improved the overall structure of your component.