Refactor this code. This is for an expo mobile app. Make… · The Chat Archive
Explore / Programming Refactor this code. This is for an expo mobile app. Make sure its dynamic. //… Save Share Download ▾ ReportRefactor this code. This is for an expo mobile app. Make sure its dynamic.
// frontend/screens/Home/ExercisesScreen.js
import React, { useEffect, useState, useContext, useCallback } from 'react';
import {
View,
Text,
FlatList,
Image,
ActivityIndicator,
Alert,
TouchableOpacity,
Linking,
TextInput,
RefreshControl,
ScrollView,
TouchableWithoutFeedback,
} from 'react-native';
import { AuthContext } from '../../context/AuthContext';
import debounce from 'lodash.debounce';
import * as SecureStore from 'expo-secure-store';
import { useTheme, Button, Portal } from 'react-native-paper';
import { Picker } from '@react-native-picker/picker';
import CustomMultiSelect from '../../Components/CustomMultiSelect';
import { api, eventEmitter } from '../../services/api';
import createStyles from './ExercisesScreenStyles'; // Import the styles factory
const ExercisesScreen = () => {
const { authToken } = useContext(AuthContext);
const [exercises, setExercises] = useState([]);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [isRefreshing, setIsRefreshing] = useState(false);
Show full message · 531 lines Assistant2024-10-09 19:29 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Oct 9, 2024
Added to archive Nov 16, 2026
ID 01m7h41x6f9nxw4zzw7xtdv1hwSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: f0046db4dfefd18fef6f05fd451fe2fb
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
const theme = useTheme(); // Accessing the theme
const styles = createStyles(theme); // Generate styles based on the theme
// Filter state
const [filterModalVisible, setFilterModalVisible] = useState(false);
const [selectedMuscles, setSelectedMuscles] = useState([]);
const [selectedEquipment, setSelectedEquipment] = useState([]);
const [selectedDifficulty, setSelectedDifficulty] = useState('');
// Selected exercise for detail modal
const [selectedExercise, setSelectedExercise] = useState(null);
const [detailModalVisible, setDetailModalVisible] = useState(false);
// Define the cache keys
const CACHE_KEY = 'cachedExercises';
const CACHE_TIMESTAMP_KEY = 'cachedExercisesTimestamp';
const MAX_CACHE_AGE = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
// Predefined options for filters
const muscleOptions = [
{ id: 'chest', name: 'Chest' },
{ id: 'back', name: 'Back' },
{ id: 'legs', name: 'Legs' },
{ id: 'arms', name: 'Arms' },
{ id: 'shoulders', name: 'Shoulders' },
// Add more muscles as needed
];
const equipmentOptions = [
{ id: 'barbell', name: 'Barbell' },
{ id: 'dumbbell', name: 'Dumbbell' },
{ id: 'kettlebell', name: 'Kettlebell' },
{ id: 'machine', name: 'Machine' },
{ id: 'bodyweight', name: 'Bodyweight' },
{ id: 'band', name: 'Band' },
{ id: 'plate', name: 'Plate' },
{ id: 'other', name: 'Other' },
// Add more equipment as needed
];
const difficultyOptions = [
{ label: 'Beginner', value: 'beginner' },
{ label: 'Intermediate', value: 'intermediate' },
{ label: 'Advanced', value: 'advanced' },
];
useEffect(() => {
loadCachedExercises();
}, [authToken]); // Reload when token changes
// Listen for logout events to handle session expiry
useEffect(() => {
const handleLogout = () => {
// Reset states or navigate to the login screen as needed
setExercises([]);
setLoading(false);
Alert.alert('Logged Out', 'You have been logged out. Please log in again.');
// Additional logout logic (e.g., navigation) can be added here
};
eventEmitter.on('logout', handleLogout);
// Cleanup subscription on unmount
return () => {
eventEmitter.off('logout', handleLogout);
};
}, []);
// Debounced fetch function to prevent multiple rapid API calls
const debouncedFetchExercises = useCallback(
debounce((query, filters) => {
fetchExercises(query, filters);
}, 300),
[authToken]
);
useEffect(() => {
console.log('selectedMuscles:', selectedMuscles);
console.log('selectedEquipment:', selectedEquipment);
console.log('selectedDifficulty:', selectedDifficulty);
if (searchQuery.length === 0 || searchQuery.length > 2) { // Trigger search after 3 characters
const filters = {
muscles: Array.isArray(selectedMuscles) ? selectedMuscles.join(',') : '',
equipment: Array.isArray(selectedEquipment) ? selectedEquipment.join(',') : '',
difficulty: selectedDifficulty,
};
debouncedFetchExercises(searchQuery, filters);
}
}, [searchQuery, selectedMuscles, selectedEquipment, selectedDifficulty, debouncedFetchExercises]);
/**
* Load exercises from SecureStore
*/
const loadCachedExercises = async () => {
if (!authToken) {
setLoading(false);
return;
}
try {
const [cachedData, cachedTimestamp] = await Promise.all([
SecureStore.getItemAsync(CACHE_KEY),
SecureStore.getItemAsync(CACHE_TIMESTAMP_KEY),
]);
if (cachedData && cachedTimestamp) {
const parsedData = JSON.parse(cachedData);
const timestamp = parseInt(cachedTimestamp, 10);
const currentTime = Date.now();
const cacheAge = currentTime - timestamp;
if (cacheAge < MAX_CACHE_AGE) {
setExercises(parsedData);
console.log('Loaded exercises from SecureStore.');
setLoading(false);
return;
} else {
console.log('Cache is stale. Fetching fresh data.');
}
} else {
console.log('No cached data found. Fetching from API.');
}
// Fetch fresh data
fetchExercises();
} catch (error) {
console.error('Error loading cached exercises:', error);
Alert.alert('Error', 'Failed to load cached exercises.');
fetchExercises();
}
};
/**
* Fetch exercises from the API with optional search and filters
* @param {string} query - Search query
* @param {object} filters - Filter parameters
*/
const fetchExercises = async (query = '', filters = {}) => {
if (!authToken) {
Alert.alert('Authentication Error', 'Please log in to fetch exercises.');
setLoading(false);
return;
}
console.log('Fetching exercises with token:', authToken);
try {
const response = await api.get('/api/exercises', {
params: {
search: query,
muscles: filters.muscles || '',
equipment: filters.equipment || '',
difficulty: filters.difficulty || '',
limit: 50,
},
});
if (response.status === 200) {
const fetchedExercises = response.data;
setExercises(fetchedExercises);
// Cache the fetched data with a timestamp
await Promise.all([
SecureStore.setItemAsync(CACHE_KEY, JSON.stringify(fetchedExercises)),
SecureStore.setItemAsync(CACHE_TIMESTAMP_KEY, Date.now().toString()),
]);
console.log('Fetched exercises from API and cached.');
} else {
console.error('Unexpected response status:', response.status);
Alert.alert('Error', 'Unexpected response from the server.');
}
} catch (error) {
// Errors are handled globally in api.js's response interceptor
console.error('Error fetching exercises:', error);
} finally {
setLoading(false);
setIsRefreshing(false);
}
};
/**
* Handle user input in the search bar
* @param {string} text - Search query text
*/
const handleSearch = (text) => {
setSearchQuery(text);
};
/**
* Handle pull-to-refresh action
*/
const onRefresh = () => {
setIsRefreshing(true);
fetchExercises(searchQuery, {
muscles: Array.isArray(selectedMuscles) ? selectedMuscles.join(',') : '',
equipment: Array.isArray(selectedEquipment) ? selectedEquipment.join(',') : '',
difficulty: selectedDifficulty,
});
};
/**
* Render each exercise item
* @param {object} item - Exercise object
*/
const renderItem = ({ item }) => (
<TouchableOpacity onPress={() => openDetailModal(item)}>
<View style={styles.itemContainer}>
{item.imageUrl ? (
<Image source={{ uri: item.imageUrl }} style={styles.image} resizeMode="cover" />
) : (
<View style={styles.imagePlaceholder}>
<Text style={styles.imagePlaceholderText}>No Image</Text>
</View>
)}
<Text style={styles.title}>
{item.name}
</Text>
{item.description ? <Text style={styles.description}>{item.description}</Text> : null}
{item.videoUrl ? (
<TouchableOpacity onPress={() => handleOpenURL(item.videoUrl)}>
<Text style={styles.link}>Video Tutorial</Text>
</TouchableOpacity>
) : null}
</View>
</TouchableOpacity>
);
/**
* Open the detail modal with exercise details
* @param {object} exercise - Selected exercise
*/
const openDetailModal = (exercise) => {
console.log('Selected Exercise:', exercise); // Debugging line
setSelectedExercise(exercise);
setDetailModalVisible(true);
};
/**
* Handle opening URLs with validation
* @param {string} url - URL to open
*/
const handleOpenURL = async (url) => {
const supported = await Linking.canOpenURL(url);
if (supported) {
await Linking.openURL(url);
} else {
Alert.alert('Invalid URL', 'Cannot open the requested URL.');
}
};
/**
* Render the filter modal using custom transparent backdrop
*/
const renderFilterModal = () => {
if (!filterModalVisible) return null; // Only render if visible
return (
<Portal>
<TouchableWithoutFeedback onPress={() => setFilterModalVisible(false)}>
<View style={styles.backdrop}>
<TouchableWithoutFeedback>
<View style={styles.modalContent}>
<ScrollView>
<Text style={styles.modalTitle}>Filter Exercises</Text>
{/* Muscle Filter */}
<CustomMultiSelect
label="Muscles"
items={muscleOptions}
selectedItems={selectedMuscles}
onSelectedItemsChange={handleSelectedMusclesChange}
placeholder="Select Muscles"
/>
{/* Equipment Filter */}
<CustomMultiSelect
label="Equipment"
items={equipmentOptions}
selectedItems={selectedEquipment}
onSelectedItemsChange={handleSelectedEquipmentChange}
placeholder="Select Equipment"
/>
{/* Difficulty Filter */}
<Text style={styles.modalLabel}>Difficulty</Text>
<View style={styles.pickerContainer}>
<Picker
selectedValue={selectedDifficulty}
onValueChange={(itemValue) => setSelectedDifficulty(itemValue)}
mode="dropdown"
style={{ color: theme.colors.text }}
>
<Picker.Item label="Select Difficulty" value="" />
{difficultyOptions.map((option) => (
<Picker.Item key={option.value} label={option.label} value={option.value} />
))}
</Picker>
</View>
{/* Apply and Reset Buttons */}
<View style={styles.modalButtons}>
<Button
mode="contained"
onPress={() => setFilterModalVisible(false)}
style={styles.modalButton}
uppercase={false}
>
Apply
</Button>
<Button
mode="outlined"
onPress={() => {
setSelectedMuscles([]);
setSelectedEquipment([]);
setSelectedDifficulty('');
}}
style={styles.modalButton}
uppercase={false}
>
Reset
</Button>
</View>
</ScrollView>
</View>
</TouchableWithoutFeedback>
</View>
</TouchableWithoutFeedback>
</Portal>
);
};
/**
* Handle selection change for muscles and equipment to ensure they are always arrays
*/
const handleSelectedMusclesChange = (items) => {
setSelectedMuscles(Array.isArray(items) ? items : []);
};
const handleSelectedEquipmentChange = (items) => {
setSelectedEquipment(Array.isArray(items) ? items : []);
};
/**
* Render the detail modal for a selected exercise with transparent backdrop
*/
const renderDetailModal = () => {
if (!detailModalVisible || !selectedExercise) return null; // Only render if visible and exercise is selected
return (
<Portal>
<TouchableWithoutFeedback onPress={() => setDetailModalVisible(false)}>
<View style={styles.backdrop}>
<TouchableWithoutFeedback>
<View style={styles.modalContent}>
<ScrollView>
<Text style={styles.modalTitle}>{selectedExercise.name}</Text>
{selectedExercise.imageUrl ? (
<Image source={{ uri: selectedExercise.imageUrl }} style={styles.detailImage} resizeMode="cover" />
) : (
<View style={styles.imagePlaceholder}>
<Text style={styles.imagePlaceholderText}>No Image</Text>
</View>
)}
{selectedExercise.description ? (
<Text style={styles.detailDescription}>
{selectedExercise.description}
</Text>
) : null}
<Text style={styles.detailLabel}>Muscles:</Text>
<Text style={styles.detailText}>{selectedExercise.muscles.join(', ')}</Text>
<Text style={styles.detailLabel}>Equipment:</Text>
<Text style={styles.detailText}>{selectedExercise.equipment.join(', ')}</Text>
<Text style={styles.detailLabel}>Difficulty:</Text>
<Text style={styles.detailText}>{capitalizeFirstLetter(selectedExercise.difficulty)}</Text>
{/* Gender Buttons */}
<View style={styles.genderButtons}>
{selectedExercise.gender?.maleUrl ? (
<Button
mode="contained"
onPress={() => handleOpenURL(selectedExercise.gender.maleUrl)}
style={styles.genderButton}
uppercase={false}
>
Male
</Button>
) : null}
{selectedExercise.gender?.femaleUrl ? (
<Button
mode="contained"
onPress={() => handleOpenURL(selectedExercise.gender.femaleUrl)}
style={styles.genderButton}
uppercase={false}
>
Female
</Button>
) : null}
</View>
<Button
mode="outlined"
onPress={() => setDetailModalVisible(false)}
style={styles.closeButton}
uppercase={false}
>
Close
</Button>
</ScrollView>
</View>
</TouchableWithoutFeedback>
</View>
</TouchableWithoutFeedback>
</Portal>
);
};
/**
* Capitalize the first letter of a string
* @param {string} string - Input string
* @returns {string} - Capitalized string
*/
const capitalizeFirstLetter = (string) => {
if (!string) return '';
return string.charAt(0).toUpperCase() + string.slice(1);
};
if (loading && exercises.length === 0) {
return (
<View style={styles.loader}>
<ActivityIndicator size="large" color={theme.colors.primary} />
</View>
);
}
return (
<View style={styles.container}>
{/* Filter Modal */}
{filterModalVisible && renderFilterModal()}
{/* Detail Modal */}
{renderDetailModal()}
<View style={styles.header}>
<TextInput
style={styles.searchBar}
placeholder="Search exercises..."
placeholderTextColor={theme.colors.placeholder}
value={searchQuery}
onChangeText={handleSearch}
autoCapitalize="none"
autoCorrect={false}
clearButtonMode="while-editing"
/>
<TouchableOpacity
style={styles.filterButton}
onPress={() => setFilterModalVisible(true)}
>
<Text style={styles.filterButtonText}>Filter</Text>
</TouchableOpacity>
</View>
<FlatList
data={exercises}
keyExtractor={(item, index) => (item._id ? item._id : index.toString())} // Fallback to index if _id is missing
renderItem={renderItem}
contentContainerStyle={styles.list}
keyboardShouldPersistTaps="handled"
refreshControl={
<RefreshControl
refreshing={isRefreshing}
onRefresh={onRefresh}
tintColor={theme.colors.primary}
colors={[theme.colors.primary, theme.colors.accent]}
progressBackgroundColor={theme.colors.surface}
/>
}
ListEmptyComponent={
!loading && (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>No exercises found.</Text>
</View>
)
}
initialNumToRender={10} // Optimize rendering
windowSize={21}
getItemLayout={(data, index) => (
{ length: 250, offset: 250 * index, index }
)}
/>
</View>
);
export default ExercisesScreen;
Certainly! Refactoring your ExercisesScreen component will enhance readability, maintainability, and scalability. We'll modularize the code by breaking it down into smaller, reusable components and creating custom hooks for data fetching and caching. This approach promotes separation of concerns and makes the codebase easier to manage.
Here's an overview of the refactoring steps:
Create Custom Hooks:
useExercises : Handles fetching, caching, and managing the exercises data.
useFilters : Manages filter states and changes.
Separate Components:
ExerciseItem : Renders individual exercise items in the list.
FilterModal : Handles the filtering UI and logic.
DetailModal : Displays detailed information about a selected exercise.
SearchHeader : Combines the search bar and filter button.
Organize Constants:
Move filter options to a separate constants file or define them within the hook/component where they're used.
Optimize Performance:
Utilize React.memo for components that depend on props to prevent unnecessary re-renders.
Optimize FlatList by properly defining keyExtractor, getItemLayout, and other performance-related props.
Enhance Error Handling:
Improve error messages and handling mechanisms to provide better user feedback.
Below is the refactored code implementing these improvements.
1. Custom Hook: useExercises.js
javascript Copy code
// hooks/useExercises.js
import { useState, useEffect, useCallback } from 'react';
import debounce from 'lodash.debounce';
import * as SecureStore from 'expo-secure-store';
import { Alert } from 'react-native';
import { api, eventEmitter } from '../services/api';
const CACHE_KEY = 'cachedExercises';
const CACHE_TIMESTAMP_KEY = 'cachedExercisesTimestamp';
const MAX_CACHE_AGE = 24 * 60 * 60 * 1000; // 24 hours
const useExercises = (authToken, searchQuery, filters) => {
const [exercises, setExercises] = useState([]);
const [loading, setLoading] = useState(true);
const [isRefreshing, setIsRefreshing] = useState(false);
const fetchExercises = async (query = '', appliedFilters = {}) => {
if (!authToken) {
Alert.alert('Authentication Error', 'Please log in to fetch exercises.');
setLoading(false);
return;
}
try {
const response = await api.get('/api/exercises', {
params: {
search: query,
muscles: appliedFilters.muscles || '',
equipment: appliedFilters.equipment || '',
difficulty: appliedFilters.difficulty || '',
limit: 50,
},
});
if (response.status === 200) {
const fetchedExercises = response.data;
setExercises(fetchedExercises);
// Cache the data
await Promise.all([
SecureStore.setItemAsync(CACHE_KEY, JSON.stringify(fetchedExercises)),
SecureStore.setItemAsync(CACHE_TIMESTAMP_KEY, Date.now().toString()),
]);
} else {
Alert.alert('Error', 'Unexpected response from the server.');
}
} catch (error) {
console.error('Error fetching exercises:', error);
Alert.alert('Error', 'Failed to fetch exercises.');
} finally {
setLoading(false);
setIsRefreshing(false);
}
};
const loadCachedExercises = async () => {
if (!authToken) {
setLoading(false);
return;
}
try {
const [cachedData, cachedTimestamp] = await Promise.all([
SecureStore.getItemAsync(CACHE_KEY),
SecureStore.getItemAsync(CACHE_TIMESTAMP_KEY),
]);
if (cachedData && cachedTimestamp) {
const parsedData = JSON.parse(cachedData);
const timestamp = parseInt(cachedTimestamp, 10);
const currentTime = Date.now();
const cacheAge = currentTime - timestamp;
if (cacheAge < MAX_CACHE_AGE) {
setExercises(parsedData);
setLoading(false);
return;
}
}
// Fetch fresh data if no cache or cache is stale
fetchExercises(searchQuery, filters);
} catch (error) {
console.error('Error loading cached exercises:', error);
Alert.alert('Error', 'Failed to load cached exercises.');
fetchExercises(searchQuery, filters);
}
};
const debouncedFetch = useCallback(debounce(fetchExercises, 300), [authToken]);
useEffect(() => {
loadCachedExercises();
}, [authToken]);
// Listen for logout events
useEffect(() => {
const handleLogout = () => {
setExercises([]);
setLoading(false);
Alert.alert('Logged Out', 'You have been logged out. Please log in again.');
};
eventEmitter.on('logout', handleLogout);
return () => {
eventEmitter.off('logout', handleLogout);
};
}, []);
// Fetch exercises when searchQuery or filters change
useEffect(() => {
if (searchQuery.length === 0 || searchQuery.length > 2) {
debouncedFetch(searchQuery, filters);
}
}, [searchQuery, filters, debouncedFetch]);
const onRefresh = () => {
setIsRefreshing(true);
fetchExercises(searchQuery, filters);
};
return {
exercises,
loading,
isRefreshing,
onRefresh,
setExercises, // Optional: Expose if manual setting is needed
};
};
export default useExercises;
2. Custom Hook: useFilters.js
javascript Copy code
// hooks/useFilters.js
import { useState } from 'react';
const useFilters = () => {
const [selectedMuscles, setSelectedMuscles] = useState([]);
const [selectedEquipment, setSelectedEquipment] = useState([]);
const [selectedDifficulty, setSelectedDifficulty] = useState('');
const handleSelectedMusclesChange = (items) => {
setSelectedMuscles(Array.isArray(items) ? items : []);
};
const handleSelectedEquipmentChange = (items) => {
setSelectedEquipment(Array.isArray(items) ? items : []);
};
const resetFilters = () => {
setSelectedMuscles([]);
setSelectedEquipment([]);
setSelectedDifficulty('');
};
return {
selectedMuscles,
selectedEquipment,
selectedDifficulty,
handleSelectedMusclesChange,
handleSelectedEquipmentChange,
setSelectedDifficulty,
resetFilters,
};
};
export default useFilters;
3. Component: ExerciseItem.js
javascript Copy code
// components/ExerciseItem.js
import React from 'react';
import { View, Text, Image, TouchableOpacity } from 'react-native';
import { useTheme } from 'react-native-paper';
import createStyles from './ExercisesScreenStyles';
const ExerciseItem = React.memo(({ item, onPress, onOpenURL }) => {
const theme = useTheme();
const styles = createStyles(theme);
return (
<TouchableOpacity onPress={() => onPress(item)}>
<View style={styles.itemContainer}>
{item.imageUrl ? (
<Image source={{ uri: item.imageUrl }} style={styles.image} resizeMode="cover" />
) : (
<View style={styles.imagePlaceholder}>
<Text style={styles.imagePlaceholderText}>No Image</Text>
</View>
)}
<Text style={styles.title}>{item.name}</Text>
{item.description ? <Text style={styles.description}>{item.description}</Text> : null}
{item.videoUrl ? (
<TouchableOpacity onPress={() => onOpenURL(item.videoUrl)}>
<Text style={styles.link}>Video Tutorial</Text>
</TouchableOpacity>
) : null}
</View>
</TouchableOpacity>
);
});
export default ExerciseItem;
4. Component: FilterModal.js
5. Component: DetailModal.js
6. Component: SearchHeader.js
javascript Copy code
// components/SearchHeader.js
import React from 'react';
import { View, TextInput, TouchableOpacity, Text } from 'react-native';
import { useTheme } from 'react-native-paper';
import createStyles from './ExercisesScreenStyles';
const SearchHeader = ({ searchQuery, onSearch, onOpenFilter }) => {
const theme = useTheme();
const styles = createStyles(theme);
return (
<View style={styles.header}>
<TextInput
style={styles.searchBar}
placeholder="Search exercises..."
placeholderTextColor={theme.colors.placeholder}
value={searchQuery}
onChangeText={onSearch}
autoCapitalize="none"
autoCorrect={false}
clearButtonMode="while-editing"
/>
<TouchableOpacity style={styles.filterButton} onPress={onOpenFilter}>
<Text style={styles.filterButtonText}>Filter</Text>
</TouchableOpacity>
</View>
);
};
export default SearchHeader;
7. Main Screen: ExercisesScreen.js
8. Styles: ExercisesScreenStyles.js
Ensure your styles support dynamic theming by using a factory function that takes the theme as an argument.
9. Notes and Recommendations
Component Directory Structure:
Organize your components and hooks in a structured manner. For example:
code Copy code
frontend/
├── components/
│ ├── ExerciseItem.js
│ ├── FilterModal.js
│ ├── DetailModal.js
│ └── SearchHeader.js
├── hooks/
│ ├── useExercises.js
│ └── useFilters.js
├── screens/
│ └── Home/
│ ├── ExercisesScreen.js
│ └── ExercisesScreenStyles.js
└── services/
└── api.js
Memoization:
The ExerciseItem component uses React.memo to prevent unnecessary re-renders when its props haven't changed.
Ensure any component receiving complex props utilizes memoization to enhance performance.
Error Handling:
The custom hooks handle errors by displaying alerts. Depending on your app's UX guidelines, you might want to implement a more sophisticated error handling mechanism, such as using a global error handler or displaying in-app notifications.
Accessibility:
Ensure that all interactive elements are accessible. For instance, adding accessible and accessibilityLabel props where necessary.
Testing:
With the refactored structure, writing unit tests for individual components and hooks becomes more straightforward. Consider implementing tests to ensure each part functions as expected.
Optimizations:
FlatList Optimizations: You've already set initialNumToRender, windowSize, and getItemLayout. Continue monitoring performance, especially with larger datasets.
Image Caching: Consider using libraries like react-native-fast-image for optimized image loading and caching.
Dynamicity:
The refactored code is more dynamic as it uses hooks and reusable components. You can easily extend filter options or exercise item layouts without modifying the core logic.
By implementing this refactored structure, your ExercisesScreen becomes more maintainable, scalable, and easier to understand. Modular components and hooks promote reusability and separation of concerns, making future enhancements or debugging more efficient.
Show full message · 920 lines Copy first response
Not yet included in a published release.
// components/FilterModal.js
import React from 'react';
import { View, Text, ScrollView, TouchableWithoutFeedback } from 'react-native';
import { Picker, Button, Portal, useTheme } from 'react-native-paper';
import CustomMultiSelect from './CustomMultiSelect';
import createStyles from './ExercisesScreenStyles';
const FilterModal = ({
visible,
onClose,
muscleOptions,
equipmentOptions,
difficultyOptions,
selectedMuscles,
selectedEquipment,
selectedDifficulty,
onMusclesChange,
onEquipmentChange,
onDifficultyChange,
onReset,
}) => {
const theme = useTheme();
const styles = createStyles(theme);
if (!visible) return null;
return (
<Portal>
<TouchableWithoutFeedback onPress={onClose}>
<View style={styles.backdrop}>
<TouchableWithoutFeedback>
<View style={styles.modalContent}>
<ScrollView>
<Text style={styles.modalTitle}>Filter Exercises</Text>
{/* Muscle Filter */}
<CustomMultiSelect
label="Muscles"
items={muscleOptions}
selectedItems={selectedMuscles}
onSelectedItemsChange={onMusclesChange}
placeholder="Select Muscles"
/>
{/* Equipment Filter */}
<CustomMultiSelect
label="Equipment"
items={equipmentOptions}
selectedItems={selectedEquipment}
onSelectedItemsChange={onEquipmentChange}
placeholder="Select Equipment"
/>
{/* Difficulty Filter */}
<Text style={styles.modalLabel}>Difficulty</Text>
<View style={styles.pickerContainer}>
<Picker
selectedValue={selectedDifficulty}
onValueChange={onDifficultyChange}
mode="dropdown"
style={{ color: theme.colors.text }}
>
<Picker.Item label="Select Difficulty" value="" />
{difficultyOptions.map((option) => (
<Picker.Item key={option.value} label={option.label} value={option.value} />
))}
</Picker>
</View>
{/* Apply and Reset Buttons */}
<View style={styles.modalButtons}>
<Button
mode="contained"
onPress={onClose}
style={styles.modalButton}
uppercase={false}
>
Apply
</Button>
<Button
mode="outlined"
onPress={onReset}
style={styles.modalButton}
uppercase={false}
>
Reset
</Button>
</View>
</ScrollView>
</View>
</TouchableWithoutFeedback>
</View>
</TouchableWithoutFeedback>
</Portal>
);
};
export default FilterModal;
// components/DetailModal.js
import React from 'react';
import { View, Text, Image, ScrollView, TouchableWithoutFeedback } from 'react-native';
import { Button, Portal, useTheme } from 'react-native-paper';
import createStyles from './ExercisesScreenStyles';
const DetailModal = ({ visible, onClose, exercise, onOpenURL }) => {
const theme = useTheme();
const styles = createStyles(theme);
if (!visible || !exercise) return null;
const capitalizeFirstLetter = (string) => {
if (!string) return '';
return string.charAt(0).toUpperCase() + string.slice(1);
};
return (
<Portal>
<TouchableWithoutFeedback onPress={onClose}>
<View style={styles.backdrop}>
<TouchableWithoutFeedback>
<View style={styles.modalContent}>
<ScrollView>
<Text style={styles.modalTitle}>{exercise.name}</Text>
{exercise.imageUrl ? (
<Image source={{ uri: exercise.imageUrl }} style={styles.detailImage} resizeMode="cover" />
) : (
<View style={styles.imagePlaceholder}>
<Text style={styles.imagePlaceholderText}>No Image</Text>
</View>
)}
{exercise.description ? (
<Text style={styles.detailDescription}>{exercise.description}</Text>
) : null}
<Text style={styles.detailLabel}>Muscles:</Text>
<Text style={styles.detailText}>{exercise.muscles.join(', ')}</Text>
<Text style={styles.detailLabel}>Equipment:</Text>
<Text style={styles.detailText}>{exercise.equipment.join(', ')}</Text>
<Text style={styles.detailLabel}>Difficulty:</Text>
<Text style={styles.detailText}>{capitalizeFirstLetter(exercise.difficulty)}</Text>
{/* Gender Buttons */}
<View style={styles.genderButtons}>
{exercise.gender?.maleUrl && (
<Button
mode="contained"
onPress={() => onOpenURL(exercise.gender.maleUrl)}
style={styles.genderButton}
uppercase={false}
>
Male
</Button>
)}
{exercise.gender?.femaleUrl && (
<Button
mode="contained"
onPress={() => onOpenURL(exercise.gender.femaleUrl)}
style={styles.genderButton}
uppercase={false}
>
Female
</Button>
)}
</View>
<Button
mode="outlined"
onPress={onClose}
style={styles.closeButton}
uppercase={false}
>
Close
</Button>
</ScrollView>
</View>
</TouchableWithoutFeedback>
</View>
</TouchableWithoutFeedback>
</Portal>
);
};
export default DetailModal;
// frontend/screens/Home/ExercisesScreen.js
import React, { useContext, useState } from 'react';
import {
View,
Text,
FlatList,
ActivityIndicator,
} from 'react-native';
import { AuthContext } from '../../context/AuthContext';
import { useTheme } from 'react-native-paper';
import CustomMultiSelect from '../../Components/CustomMultiSelect';
import useExercises from '../../hooks/useExercises';
import useFilters from '../../hooks/useFilters';
import ExerciseItem from '../../components/ExerciseItem';
import FilterModal from '../../components/FilterModal';
import DetailModal from '../../components/DetailModal';
import SearchHeader from '../../components/SearchHeader';
import createStyles from './ExercisesScreenStyles';
const ExercisesScreen = () => {
const { authToken } = useContext(AuthContext);
const theme = useTheme();
const styles = createStyles(theme);
// Filter management
const {
selectedMuscles,
selectedEquipment,
selectedDifficulty,
handleSelectedMusclesChange,
handleSelectedEquipmentChange,
setSelectedDifficulty,
resetFilters,
} = useFilters();
// State for modals
const [filterModalVisible, setFilterModalVisible] = useState(false);
const [detailModalVisible, setDetailModalVisible] = useState(false);
const [selectedExercise, setSelectedExercise] = useState(null);
// Search query
const [searchQuery, setSearchQuery] = useState('');
// Fetch exercises using custom hook
const {
exercises,
loading,
isRefreshing,
onRefresh,
} = useExercises(authToken, searchQuery, {
muscles: selectedMuscles.join(','),
equipment: selectedEquipment.join(','),
difficulty: selectedDifficulty,
});
// Predefined filter options
const muscleOptions = [
{ id: 'chest', name: 'Chest' },
{ id: 'back', name: 'Back' },
{ id: 'legs', name: 'Legs' },
{ id: 'arms', name: 'Arms' },
{ id: 'shoulders', name: 'Shoulders' },
// Add more muscles as needed
];
const equipmentOptions = [
{ id: 'barbell', name: 'Barbell' },
{ id: 'dumbbell', name: 'Dumbbell' },
{ id: 'kettlebell', name: 'Kettlebell' },
{ id: 'machine', name: 'Machine' },
{ id: 'bodyweight', name: 'Bodyweight' },
{ id: 'band', name: 'Band' },
{ id: 'plate', name: 'Plate' },
{ id: 'other', name: 'Other' },
// Add more equipment as needed
];
const difficultyOptions = [
{ label: 'Beginner', value: 'beginner' },
{ label: 'Intermediate', value: 'intermediate' },
{ label: 'Advanced', value: 'advanced' },
];
// Handlers
const handleSearch = (text) => {
setSearchQuery(text);
};
const openFilterModal = () => {
setFilterModalVisible(true);
};
const closeFilterModal = () => {
setFilterModalVisible(false);
};
const handleOpenURL = async (url) => {
const supported = await Linking.canOpenURL(url);
if (supported) {
await Linking.openURL(url);
} else {
Alert.alert('Invalid URL', 'Cannot open the requested URL.');
}
};
const openDetailModal = (exercise) => {
setSelectedExercise(exercise);
setDetailModalVisible(true);
};
const closeDetailModal = () => {
setDetailModalVisible(false);
setSelectedExercise(null);
};
// Render
if (loading && exercises.length === 0) {
return (
<View style={styles.loader}>
<ActivityIndicator size="large" color={theme.colors.primary} />
</View>
);
}
return (
<View style={styles.container}>
{/* Search and Filter Header */}
<SearchHeader
searchQuery={searchQuery}
onSearch={handleSearch}
onOpenFilter={openFilterModal}
/>
{/* Filter Modal */}
<FilterModal
visible={filterModalVisible}
onClose={closeFilterModal}
muscleOptions={muscleOptions}
equipmentOptions={equipmentOptions}
difficultyOptions={difficultyOptions}
selectedMuscles={selectedMuscles}
selectedEquipment={selectedEquipment}
selectedDifficulty={selectedDifficulty}
onMusclesChange={handleSelectedMusclesChange}
onEquipmentChange={handleSelectedEquipmentChange}
onDifficultyChange={setSelectedDifficulty}
onReset={resetFilters}
/>
{/* Detail Modal */}
<DetailModal
visible={detailModalVisible}
onClose={closeDetailModal}
exercise={selectedExercise}
onOpenURL={handleOpenURL}
/>
{/* Exercises List */}
<FlatList
data={exercises}
keyExtractor={(item, index) => (item._id ? item._id : index.toString())}
renderItem={({ item }) => (
<ExerciseItem
item={item}
onPress={openDetailModal}
onOpenURL={handleOpenURL}
/>
)}
contentContainerStyle={styles.list}
keyboardShouldPersistTaps="handled"
refreshControl={
<RefreshControl
refreshing={isRefreshing}
onRefresh={onRefresh}
tintColor={theme.colors.primary}
colors={[theme.colors.primary, theme.colors.accent]}
progressBackgroundColor={theme.colors.surface}
/>
}
ListEmptyComponent={
!loading && (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>No exercises found.</Text>
</View>
)
}
initialNumToRender={10}
windowSize={21}
getItemLayout={(data, index) => (
{ length: 250, offset: 250 * index, index }
)}
/>
</View>
);
};
export default ExercisesScreen;
// frontend/screens/Home/ExercisesScreenStyles.js
import { StyleSheet } from 'react-native';
const createStyles = (theme) => StyleSheet.create({
container: {
flex: 1,
backgroundColor: theme.colors.background,
},
loader: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
header: {
flexDirection: 'row',
padding: 10,
alignItems: 'center',
backgroundColor: theme.colors.surface,
},
searchBar: {
flex: 1,
height: 40,
backgroundColor: theme.colors.background,
borderRadius: 5,
paddingHorizontal: 10,
color: theme.colors.text,
},
filterButton: {
marginLeft: 10,
padding: 10,
backgroundColor: theme.colors.primary,
borderRadius: 5,
},
filterButtonText: {
color: theme.colors.background,
fontWeight: 'bold',
},
list: {
padding: 10,
},
itemContainer: {
backgroundColor: theme.colors.surface,
padding: 15,
marginBottom: 10,
borderRadius: 10,
elevation: 2,
},
image: {
width: '100%',
height: 150,
borderRadius: 10,
},
imagePlaceholder: {
width: '100%',
height: 150,
borderRadius: 10,
backgroundColor: theme.colors.placeholder,
justifyContent: 'center',
alignItems: 'center',
},
imagePlaceholderText: {
color: theme.colors.text,
fontSize: 16,
},
title: {
fontSize: 18,
fontWeight: 'bold',
marginTop: 10,
color: theme.colors.text,
},
description: {
fontSize: 14,
marginTop: 5,
color: theme.colors.text,
},
link: {
fontSize: 14,
color: theme.colors.primary,
marginTop: 5,
},
emptyContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
marginTop: 50,
},
emptyText: {
fontSize: 18,
color: theme.colors.text,
},
backdrop: {
flex: 1,
backgroundColor: 'rgba(0,0,0,0.5)',
justifyContent: 'center',
padding: 20,
},
modalContent: {
backgroundColor: theme.colors.background,
borderRadius: 10,
padding: 20,
maxHeight: '80%',
},
modalTitle: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 20,
color: theme.colors.text,
alignSelf: 'center',
},
modalLabel: {
fontSize: 16,
fontWeight: '500',
marginTop: 10,
color: theme.colors.text,
},
pickerContainer: {
borderWidth: 1,
borderColor: theme.colors.placeholder,
borderRadius: 5,
marginTop: 5,
},
modalButtons: {
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 20,
},
modalButton: {
flex: 1,
marginHorizontal: 5,
},
detailImage: {
width: '100%',
height: 200,
borderRadius: 10,
},
detailDescription: {
fontSize: 16,
marginTop: 10,
color: theme.colors.text,
},
detailLabel: {
fontSize: 16,
fontWeight: '600',
marginTop: 10,
color: theme.colors.text,
},
detailText: {
fontSize: 16,
color: theme.colors.text,
},
genderButtons: {
flexDirection: 'row',
justifyContent: 'space-around',
marginTop: 20,
},
genderButton: {
flex: 1,
marginHorizontal: 5,
},
closeButton: {
marginTop: 20,
},
});
export default createStyles;
ExercisesScreen
Styling:
Ensure your theme object includes all necessary colors and styles to support dark/light modes and other theming requirements.
If styles become too large, consider splitting them into multiple style files based on components.