Certainly! Your current implementation involves repetitive patterns for handling API calls, error handling, and state management. We can optimize your code by:
- Creating a Generic API Handler: This reduces duplication by abstracting the common logic into a reusable function.
- Using Proper TypeScript Types: Replace
any with more specific types to enhance type safety.
- Improving Error Handling: Handle errors more gracefully by differentiating between network errors and API-specific errors.
- Enhancing Readability: Organize the code for better maintainability.
Below is the optimized version of your code incorporating these improvements:
import React, { useState } from 'react';
import {
View,
Text,
ScrollView,
StyleSheet,
Button as RNButton, // Assuming you are using React Native Button
} from 'react-native';
import Background from './Background'; // Adjust the import paths as necessary
import DaikinLiteWifiAlert from './DaikinLiteWifiAlert';
import Alert from './Alert';
import Label from './Label';
import { althermaService, isConnectedToSSIDPrefix, timeout } from './services'; // Adjust the import paths
import {
iWLANNetwork,
iWLANScanResponse,
iWLANSettings,
iWLANInfo,
iNetworkResult,
iNetworkError
} from './types'; // Adjust the import paths
interface AlertStatus {
isVisible: boolean;
buttonAlignment: string;
title: string;
message: string;
positiveBtnLabel?: string;
negativeBtnLabel?: string;
alternativeBtnLabel?: string;
onPress?: () => void;
onCancel?: () => void;
onPressAlternate?: () => void;
}
// Define your styles here or import from a separate file
const styles = StyleSheet.create({
root: { flex: 1 },
container: { padding: 16 },
description: { marginBottom: 16 },
scanButton: { marginVertical: 8 },
responseWrapper: { flex: 1, marginTop: 16 },
responseContainer: { flex: 1 },
responseText: { fontSize: 14 },
});
const ALTHERMA_SSID = 'Your_SSID_Prefix'; // Replace with your actual SSID prefix
const MINI_SPLIT_CONNECT_TIMEOUT = 5000; // Example timeout value
const YourComponent = ({ navigation, routes }) => {
const [apiResponse, setApiResponse] = useState<string>('');
const [alertStatus, setAlertStatus] = useState<AlertStatus>({
isVisible: false,
buttonAlignment: 'center',
title: '',
message: '',
});
const showLoader = (show: boolean) => {
// Implement your loader visibility logic here
};
// Generic API handler
const handleApiCall = async <T>(
apiCall: () => Promise<iNetworkResult<T> | iNetworkError>,
successMessage: string = 'Success',
errorMessage: string = 'Error'
) => {
showLoader(true);
try {
const result = await apiCall();
if ('error' in result && result.error) {
setApiResponse(`${errorMessage}: ${JSON.stringify(result.error)}`);
} else {
setApiResponse(`${successMessage}: ${JSON.stringify(result.data)}`);
}
} catch (error: unknown) {
if (error instanceof Error) {
setApiResponse(`Exception: ${error.message}`);
} else {
setApiResponse('An unknown error occurred.');
}
} finally {
showLoader(false);
}
};
// Specific API handlers using the generic handler
const runScanApi = () => {
handleApiCall<iWLANScanResponse>(
() => althermaService.scanWifiNetworks(),
'Scan API Success',
'Scan API Error'
);
};
const runNetworksApi = () => {
handleApiCall<iWLANNetwork[]>(
() => althermaService.getAvailableNetworks(),
'Networks API Success',
'Networks API Error'
);
};
const runSettingsApi = (shouldReset: boolean = false) => {
const settings: iWLANSettings = {
ssid: shouldReset ? "" : "Hathway_Ashish2.4G",
security: shouldReset ? "" : "WPA_WPA2_MIXED",
key: shouldReset ? "" : "8296494290",
};
handleApiCall<iWLANInfo>(
() => althermaService.configureWifiConnection(settings),
'Settings API Success',
'Settings API Error'
);
};
const runInfoApi = () => {
handleApiCall<iWLANInfo>(
() => althermaService.getWlanInfo(),
'Info API Success',
'Info API Error'
);
};
const navigateBack = () => {
showLoader(false);
const isConfigureThermostatScreenPresent = routes.some(
(item) => item.name === "ConfigureThermostatScreen"
);
if (isConfigureThermostatScreenPresent) {
navigation.pop(1);
} else {
navigation.goBack();
}
};
const reboot = async () => {
showLoader(true);
try {
const isConnectedToMiniSplitSSID = await isConnectedToSSIDPrefix(ALTHERMA_SSID);
if (isConnectedToMiniSplitSSID.isConnected) {
await handleApiCall<iWLANInfo>(
() => althermaService.configureWifiConnection({
ssid: "",
security: "",
key: "",
}),
'Reboot API Success',
'Reboot API Error'
);
await timeout(MINI_SPLIT_CONNECT_TIMEOUT);
}
} finally {
navigateBack();
}
};
const onDismissAlert = () => {
setAlertStatus((prevStatus) => ({
...prevStatus,
isVisible: false,
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 || "Okay" // Replace with your translation logic
}
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}
/>
<RNButton
title="Run Scan API"
onPress={runScanApi}
/>
<RNButton
title="Run Networks API"
onPress={runNetworksApi}
/>
<RNButton
title="Run Settings API"
onPress={() => runSettingsApi(false)}
/>
<RNButton
title="Run Info API"
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>
);
};
export default YourComponent;
Detailed Breakdown of Optimizations
-
Generic API Handler (handleApiCall):
- Purpose: Encapsulates the common logic for making API calls, handling success and error responses, and managing the loader state.
- Usage: Pass the specific API call as a function, along with optional success and error messages.
- Type Safety: Utilizes TypeScript generics to handle different API response types, ensuring that the
data property matches the expected type.
const handleApiCall = async <T>(
apiCall: () => Promise<iNetworkResult<T> | iNetworkError>,
successMessage: string = 'Success',
errorMessage: string = 'Error'
) => {
showLoader(true);
try {
const result = await apiCall();
if ('error' in result && result.error) {
setApiResponse(`${errorMessage}: ${JSON.stringify(result.error)}`);
} else {
setApiResponse(`${successMessage}: ${JSON.stringify(result.data)}`);
}
} catch (error: unknown) {
if (error instanceof Error) {
setApiResponse(`Exception: ${error.message}`);
} else {
setApiResponse('An unknown error occurred.');
}
} finally {
showLoader(false);
}
};
-
Specific API Handlers:
- Simplification: Each specific API handler (
runScanApi, runNetworksApi, runSettingsApi, runInfoApi) now leverages the generic handleApiCall function, reducing code duplication.
- Type Safety: Each handler specifies the expected data type, ensuring that TypeScript can validate the response correctly.
const runScanApi = () => {
handleApiCall<iWLANScanResponse>(
() => althermaService.scanWifiNetworks(),
'Scan API Success',
'Scan API Error'
);
};
const runNetworksApi = () => {
handleApiCall<iWLANNetwork[]>(
() => althermaService.getAvailableNetworks(),
'Networks API Success',
'Networks API Error'
);
};
const runSettingsApi = (shouldReset: boolean = false) => {
const settings: iWLANSettings = {
ssid: shouldReset ? "" : "Hathway_Ashish2.4G",
security: shouldReset ? "" : "WPA_WPA2_MIXED",
key: shouldReset ? "" : "8296494290",
};
handleApiCall<iWLANInfo>(
() => althermaService.configureWifiConnection(settings),
'Settings API Success',
'Settings API Error'
);
};
const runInfoApi = () => {
handleApiCall<iWLANInfo>(
() => althermaService.getWlanInfo(),
'Info API Success',
'Info API Error'
);
};
-
Enhanced Error Handling:
- Type Narrowing: Replaced with and then checked if is an instance of . This approach is safer and aligns with TypeScript best practices.
Additional Recommendations
-
Error Logging:
- Consider logging errors to an external service or the console for easier debugging.
catch (error: unknown) {
if (error instanceof Error) {
console.error(error);
setApiResponse(`Exception: ${error.message}`);
} else {
console.error('Unknown error:', error);
setApiResponse('An unknown error occurred.');
}
}
-
User Feedback:
- Provide more user-friendly messages or utilize different UI elements (like toasts) to inform users about the API call statuses.
-
Loading States:
- If multiple API calls can occur simultaneously, consider managing loading states individually rather than using a single loader state.
-
Type Definitions Enhancements:
- Ensure that your
iNetworkResult and iNetworkError interfaces accurately reflect all possible responses from your API. You might need to adjust them based on the actual API responses.
-
Async/Await Error Handling:
- Always handle promises correctly to avoid unhandled promise rejections.
By implementing these optimizations, your code becomes more maintainable, type-safe, and scalable. It also enhances the overall developer experience by reducing redundancy and improving clarity.