Certainly! To remove all loading indicators (ActivityIndicator) from your HomeScreen.tsx, you'll need to eliminate both the visual components and the associated logic that manages their visibility. Here's a step-by-step guide along with the updated code:
Steps to Remove Loading Indicators:
-
Remove ActivityIndicator Imports:
- Delete
ActivityIndicator from the import statement.
-
Eliminate Loading States and Logic:
- Remove State Variables:
isGlobalLoading and setIsGlobalLoading.
- Remove
useEffect Hook:
- The
useEffect that manages isGlobalLoading should be removed.
- Remove
loading from Context Destructuring:
- If you're no longer using the
loading state from useApp, remove it from the destructured variables.
-
Adjust JSX Rendering Logic:
- Remove Conditional Rendering Based on
loading:
- Instead of conditionally rendering
ActivityIndicator or the content, always render the content (either the FlatList or the empty view).
- Remove Global Loading Overlay:
- Delete the
loadingOverlay view that displays the global ActivityIndicator.
-
Clean Up Unused Variables and Imports:
- Ensure that any variables or imports related to loading are removed to keep the code clean.
-
Verify Functionality:
- Ensure that removing the loading indicators doesn't affect other functionalities like pull-to-refresh or chat creation. The
isCreatingChat state is still useful to prevent multiple chat creations simultaneously.
Updated HomeScreen.tsx Without Loading Indicators
// src/screens/HomeScreen.tsx
import React, { useCallback, useContext, useState } from 'react';
import {
View,
FlatList,
Image,
TouchableOpacity,
StyleSheet,
SafeAreaView,
useWindowDimensions,
RefreshControl,
ScrollView,
Alert,
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { useNavigation } from '@react-navigation/native';
import { HistoricalFigure } from '../types/types';
import CustomText from '../components/CustomText';
import { Ionicons } from '@expo/vector-icons';
import { useApp } from '../context/AppContext';
import { ChatContext } from '../context/ChatContext';
import { CoinContext } from '../context/CoinContext';
import uuid from 'react-native-uuid'; // Ensure correct import
import AsyncStorage from '@react-native-async-storage/async-storage';
const HomeScreen = () => {
const navigation = useNavigation();
const {
historicalFigures,
refreshing,
t,
currentTheme,
refreshFigures,
categories,
} = useApp();
const { width } = useWindowDimensions();
const { addChat } = useContext(ChatContext);
const { coins, showRewardedAd } = useContext(CoinContext);
const [selectedCategory, setSelectedCategory] = useState<string>('All');
const [isCreatingChat, setIsCreatingChat] = useState<boolean>(false); // Keep if needed
const numColumns = 2;
const startChat = useCallback(async (figure: HistoricalFigure) => {
if (isCreatingChat) return; // Prevent multiple chat creations
setIsCreatingChat(true); // Set loading state
try {
const chatId = uuid.v4().toString();
console.log('Generated chatId:', chatId); // Logging for debugging
await addChat({
id: chatId,
figure,
createdAt: Date.now(),
});
navigation.navigate('Chat', { chatId, figure });
} catch (error) {
console.error('Error starting chat:', error);
Alert.alert(t('error'), t('errorStartingChat'));
} finally {
setIsCreatingChat(false); // Reset loading state
}
}, [addChat, navigation, t, isCreatingChat]);
const renderFigureItem = useCallback(({ item }: { item: HistoricalFigure }) => (
<TouchableOpacity
style={[styles.figureItem, { backgroundColor: currentTheme.cardBackground }]}
onPress={() => startChat(item)}
disabled={isCreatingChat} // Disable while creating
>
<Image source={{ uri: item.image }} style={styles.avatar} />
<View style={styles.figureTextContainer}>
<CustomText bold style={[styles.figureName, { color: currentTheme.textColor }]}>
{item.name}
</CustomText>
<CustomText style={[styles.figureCategory, { color: currentTheme.accentColor }]}>
{item.category}
</CustomText>
<CustomText
style={[styles.figureDescription, { color: currentTheme.secondaryTextColor }]}
numberOfLines={3}
>
{item.description}
</CustomText>
<CustomText style={[styles.popularity, { color: currentTheme.accentColor }]}>
{t('popularity')} {item.popularity || 0}
</CustomText>
</View>
</TouchableOpacity>
), [currentTheme, startChat, t, isCreatingChat]);
const keyExtractor = useCallback((item: HistoricalFigure) => item.id, []);
const onRefresh = useCallback(async () => {
await refreshFigures(); // This will handle refreshing state in AppContext
}, [refreshFigures]);
const filteredFigures = selectedCategory === 'All'
? historicalFigures
: historicalFigures.filter(fig => fig.category === selectedCategory);
const renderCategoryItem = useCallback((category: string, index: number) => {
const isSelected = category === selectedCategory;
return (
<TouchableOpacity
key={`${category}-${index}`} // Ensure each item has a unique key
style={[
styles.categoryButton,
{
backgroundColor: isSelected ? currentTheme.accentColor : 'transparent',
borderColor: isSelected ? currentTheme.accentColor : currentTheme.secondaryTextColor,
}
]}
onPress={() => setSelectedCategory(category)}
>
<CustomText
style={[
styles.categoryText,
{
color: isSelected ? currentTheme.backgroundColor : currentTheme.textColor,
}
]}
>
{t(category)}
</CustomText>
</TouchableOpacity>
);
}, [selectedCategory, currentTheme, t]);
const renderCategoryRows = () => {
// Display categories in two rows for better organization
const halfLength = Math.ceil(categories.length / 2);
return (
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.categoryRowsContainer}
>
<View>
<View style={styles.categoryRow}>
{categories.slice(0, halfLength).map((category, index) => renderCategoryItem(category, index))}
</View>
<View style={styles.categoryRow}>
{categories.slice(halfLength).map((category, index) => renderCategoryItem(category, index + halfLength))}
</View>
</View>
</ScrollView>
);
};
return (
<SafeAreaView style={[styles.safeArea, { backgroundColor: currentTheme.backgroundColor }]}>
<StatusBar style={currentTheme.statusBarStyle} />
<View style={styles.container}>
{/* Header */}
<View style={styles.header}>
<CustomText bold style={[styles.title, { color: currentTheme.textColor }]}>
{t('historicalFigures')}
</CustomText>
<View style={styles.headerRight}>
{/* Coin Display */}
<TouchableOpacity style={styles.coinContainer} onPress={showRewardedAd}>
<Ionicons name="flash" size={20} color={currentTheme.accentColor} />
<CustomText style={[styles.coinText, { color: currentTheme.textColor }]}>
{coins}
</CustomText>
</TouchableOpacity>
{/* Settings Button */}
<TouchableOpacity
style={styles.settingsButton}
onPress={() => navigation.navigate('Settings')}
>
<Ionicons name="settings-outline" size={24} color={currentTheme.accentColor} />
</TouchableOpacity>
</View>
</View>
{/* Category Selector (Two Rows, Scrollable Horizontally) */}
{renderCategoryRows()}
{/* Content */}
{filteredFigures.length === 0 ? (
<View style={styles.emptyContainer}>
<CustomText style={[styles.emptyText, { color: currentTheme.textColor }]}>
{t('noFiguresInThisCategory')}
</CustomText>
</View>
) : (
<FlatList
data={filteredFigures}
renderItem={renderFigureItem}
keyExtractor={keyExtractor}
contentContainerStyle={styles.figureList}
numColumns={numColumns}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
colors={[currentTheme.accentColor]}
tintColor={currentTheme.accentColor}
/>
}
/>
)}
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
safeArea: {
flex: 1,
},
container: {
flex: 1,
paddingHorizontal: 10,
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingVertical: 15,
paddingHorizontal: 15,
},
title: {
fontFamily: 'Poppins_700Bold',
fontSize: 24,
},
headerRight: {
flexDirection: 'row',
alignItems: 'center',
},
coinContainer: {
flexDirection: 'row',
alignItems: 'center',
padding: 5,
},
coinText: {
fontFamily: 'Poppins_700Bold',
fontSize: 18,
marginLeft: 5,
},
settingsButton: {
padding: 2,
marginLeft: 15, // Increased spacing for better visual separation
},
categoryRowsContainer: {
paddingHorizontal: 5,
paddingBottom: 20,
},
categoryRow: {
flexDirection: 'row',
marginBottom: 6,
},
categoryButton: {
paddingVertical: 8,
paddingHorizontal: 10, // Increased padding for better touch area
borderRadius: 16,
borderWidth: 1,
marginRight: 5, // Increased margin for better spacing
},
categoryText: {
fontFamily: 'Poppins_600SemiBold',
fontSize: 14,
},
figureList: {
paddingVertical: 10,
},
figureItem: {
borderRadius: 12,
elevation: 3,
flex: 1,
margin: 5,
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.22,
shadowRadius: 2.22,
shadowColor: '#000',
},
avatar: {
borderTopLeftRadius: 12,
borderTopRightRadius: 12,
height: 120, // Uniform height across all images
width: '100%', // Span the full width of the figure item
resizeMode: 'cover', // Cover ensures the image fills the space without distortion
},
figureTextContainer: {
padding: 10,
},
figureName: {
fontFamily: 'Poppins_700Bold',
fontSize: 16,
textAlign: 'center',
marginBottom: 4,
},
figureCategory: {
fontFamily: 'Poppins_600SemiBold',
textAlign: 'center',
fontSize: 12,
marginBottom: 4,
},
figureDescription: {
fontFamily: 'Poppins_400Regular',
fontSize: 14,
textAlign: 'center',
marginBottom: 4,
},
popularity: {
textAlign: 'center',
fontSize: 14,
fontFamily: 'Poppins_600SemiBold',
},
emptyContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
emptyText: {
fontSize: 16,
textAlign: 'center',
},
// Removed styles related to loading
});
export default HomeScreen;
Changes Made:
-
Imports:
- Removed
ActivityIndicator from the react-native imports.
-
State and Effects:
- Removed
isGlobalLoading state and its associated useEffect since it's no longer needed for managing loading indicators.
- Removed
loading from the useApp destructuring as it's no longer used.
-
JSX Rendering:
- Eliminated the conditional rendering of the central
ActivityIndicator.
- Removed the
loadingOverlay which was previously used to display a global loading indicator.
- The content now directly checks if
filteredFigures is empty and renders accordingly.
-
Styles:
- Removed styles related to loading indicators (
loadingContainer and loadingOverlay), ensuring the stylesheet is clean.
-
Functionality:
- Preserved the
isCreatingChat state to prevent multiple chat creations. This state no longer triggers any loading indicators but still plays its role in the logic.
Additional Recommendations:
By following these changes, your HomeScreen will no longer display any loading indicators (ActivityIndicator), resulting in a cleaner UI as per your requirements.