Certainly! Below is the revised React Native code tailored for an Expo environment. This version addresses all potential issues and ensures compatibility with Expo's ecosystem. Here's a breakdown of the key changes and fixes applied:
-
Icon Library Adjustment:
- Old:
react-native-vector-icons/Ionicons
- New:
@expo/vector-icons/Ionicons
- Reason: Expo comes pre-configured with
@expo/vector-icons, making it easier to manage icons without additional setup.
-
AsyncStorage Integration:
- Old:
AsyncStorage was used without being imported.
- New: Imported from
@react-native-async-storage/async-storage.
- Reason: AsyncStorage is essential for storing and retrieving data, such as the access token.
-
String Template Corrections:
- Fixed issues with string interpolation, especially in the
Authorization header and image URIs, by using backticks appropriately.
-
Error Handling Enhancements:
- Replaced
alert with Alert.alert for better user feedback and consistency.
-
Styling and Layout:
- Ensured that all UI components are styled correctly and that the layout is consistent across different sections.
-
Navigation Enhancements:
- Added
headerShown: false to hide default headers in the tab navigator for a cleaner look.
-
Dependency Management:
- Remember to install necessary packages when using Expo.
Below is the complete, updated code:
import React, { useEffect, useState } from 'react';
import {
View,
Text,
Image,
ScrollView,
TextInput,
TouchableOpacity,
StyleSheet,
Alert,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons'; // Updated Icon import
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage'; // Imported AsyncStorage
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
const Tab = createBottomTabNavigator();
const MenuScreen = () => {
const [categories, setCategories] = useState([]);
const [popularItems, setPopularItems] = useState([]);
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
try {
const response = await axios.get('https://foodbyte.pythonanywhere.com/home/');
setCategories(response.data.categories);
setPopularItems(response.data.popularitems);
} catch (error) {
console.error('Error fetching data:', error);
Alert.alert('Error', 'Failed to fetch data.');
}
};
const addToCart = async (itemName) => {
try {
const token = await AsyncStorage.getItem('access_token');
if (!token) {
Alert.alert('Authentication Required', 'Please log in to add items to your cart.');
return;
}
// Create the headers object with the authorization token
const headers = {
Authorization: `Bearer ${token}`, // Fixed template literals
};
// Send the POST request to add the item to the cart
await axios.post(`https://foodbyte.pythonanywhere.com/Cartaccess/${itemName}`, {}, { headers });
// Notify user of success
Alert.alert('Success', 'Item added to cart!');
} catch (error) {
// Handle any errors
console.error('Error adding to cart:', error);
Alert.alert('Error', 'Failed to add item to cart.');
}
};
return (
<ScrollView style={styles.container}>
{/* Header Section */}
<View style={styles.header}>
<Text style={styles.menuTitle}>Menu</Text>
<Ionicons name="person-circle-outline" size={30} color="#fff" />
</View>
{/* Search Bar */}
<View style={styles.searchSection}>
<Ionicons name="search-outline" size={20} color="#000" />
<TextInput placeholder="Search" style={styles.searchInput} />
</View>
{/* Categories */}
<ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.categories}>
{categories.map((category, index) => (
<View key={index} style={styles.category}>
<Image
source={{ uri: `https://foodbyte.pythonanywhere.com${category.category_img}` }} // Fixed URI
style={styles.categoryImage}
/>
<Text style={styles.categoryText}>{category.category_name}</Text>
</View>
))}
</ScrollView>
{/* Specials Section */}
<View style={styles.specials}>
<Text style={styles.specialsText}>Specials</Text>
<Text style={styles.offerText}>Flat 50% OFF Combo Pack of the day</Text>
</View>
{/* Popular Items */}
<Text style={styles.popularTitle}>Popular</Text>
<View style={styles.popularItems}>
{popularItems.map((item, index) => (
<View key={index} style={styles.popularCard}>
<Image
source={{ uri: `https://foodbyte.pythonanywhere.com${item.item_img}` }} // Fixed URI
style={styles.popularImage}
/>
<Text style={styles.itemName}>{item.item_name}</Text>
<Text style={styles.itemPrice}>₹{item.item_price}</Text>
<TouchableOpacity style={styles.addButton} onPress={() => addToCart(item.item_name)}>
<Ionicons name="cart-outline" size={20} color="#00c853" />
</TouchableOpacity>
</View>
))}
</View>
</ScrollView>
);
};
const ProfileScreen = () => (
<View style={styles.centered}>
<Text style={styles.screenText}>Profile Screen</Text>
</View>
);
const CartScreen = () => (
<View style={styles.centered}>
<Text style={styles.screenText}>Cart Screen</Text>
</View>
);
const OrdersScreen = () => (
<View style={styles.centered}>
<Text style={styles.screenText}>Orders Screen</Text>
</View>
);
const App = () => {
return (
<NavigationContainer>
<Tab.Navigator
screenOptions={({ route }) => ({
headerShown: false, // Hide headers in tab screens
tabBarIcon: ({ color, size }) => {
let iconName;
if (route.name === 'Home') {
iconName = 'home-outline';
} else if (route.name === 'Profile') {
iconName = 'person-outline';
} else if (route.name === 'Cart') {
iconName = 'cart-outline';
} else if (route.name === 'Orders') {
iconName = 'receipt-outline';
}
return <Ionicons name={iconName} size={size} color={color} />;
},
tabBarActiveTintColor: '#ff0066',
tabBarInactiveTintColor: 'gray',
})}
>
<Tab.Screen name="Home" component={MenuScreen} />
<Tab.Screen name="Profile" component={ProfileScreen} />
<Tab.Screen name="Cart" component={CartScreen} />
<Tab.Screen name="Orders" component={OrdersScreen} />
</Tab.Navigator>
</NavigationContainer>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ff0066',
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
padding: 20,
},
menuTitle: {
color: '#fff',
fontSize: 24,
fontWeight: 'bold',
},
searchSection: {
flexDirection: 'row',
backgroundColor: '#fff',
marginHorizontal: 20,
paddingHorizontal: 10,
paddingVertical: 8,
borderRadius: 20,
alignItems: 'center',
marginVertical: 10,
},
searchInput: {
marginLeft: 10,
fontSize: 16,
color: '#000',
flex: 1,
},
categories: {
flexDirection: 'row',
marginVertical: 10,
paddingHorizontal: 20,
},
category: {
alignItems: 'center',
marginHorizontal: 10,
},
categoryImage: {
width: 60,
height: 60,
borderRadius: 30,
},
categoryText: {
marginTop: 5,
color: '#fff',
},
specials: {
backgroundColor: '#440099',
padding: 20,
marginVertical: 10,
marginHorizontal: 20,
borderRadius: 10,
},
specialsText: {
color: '#fff',
fontSize: 20,
fontWeight: 'bold',
},
offerText: {
color: '#fff',
fontSize: 16,
marginTop: 5,
},
popularTitle: {
color: '#fff',
fontSize: 24,
fontWeight: 'bold',
marginHorizontal: 20,
marginVertical: 10,
},
popularItems: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-between',
paddingHorizontal: 20,
},
popularCard: {
backgroundColor: '#fff',
borderRadius: 10,
width: '48%',
marginVertical: 10,
padding: 10,
alignItems: 'center',
elevation: 3, // Added elevation for shadow on Android
shadowColor: '#000', // Added shadow for iOS
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
},
popularImage: {
width: 100,
height: 100,
borderRadius: 10,
},
itemName: {
marginTop: 10,
fontSize: 16,
color: '#000',
textAlign: 'center', // Ensures text is centered
},
itemPrice: {
color: '#00c853',
fontSize: 16,
fontWeight: 'bold',
marginVertical: 5,
},
addButton: {
marginTop: 10,
},
centered: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
screenText: {
fontSize: 18,
color: '#333',
},
});
export default App;
Key Points to Note:
-
Dependencies:
-
AsyncStorage Usage:
- Replace the placeholder comment with your actual logic for storing and retrieving the access token.
- Ensure that the
access_token is correctly stored after user authentication.
-
Error Handling:
- Enhanced error handling provides better user feedback using
Alert.alert instead of the basic alert.
-
Styling Enhancements:
- Added shadows and elevations to cards for better visual appeal.
- Ensured text is centered where necessary for a cleaner look.
-
Navigation Configuration:
- Hidden the default header in the tab navigator for a more streamlined interface.
-
Image URIs:
- Corrected the URI strings using backticks to ensure proper interpolation.
-
Icon Components:
- Swapped out
react-native-vector-icons for @expo/vector-icons, which is optimized for Expo projects.
Final Steps:
-
Run the Project:
- After setting up, run your Expo project using:
expo start
- Use the Expo Go app or an emulator to view your application.
-
Testing:
- Ensure that all functionalities, especially network requests and storage operations, work as expected.
- Test on both Android and iOS devices or simulators to verify compatibility.
-
Further Enhancements:
- Consider adding user authentication flows to handle access tokens securely.
- Improve UI/UX based on user feedback or design guidelines.
This updated code should work seamlessly within an Expo environment, providing a robust foundation for your food delivery application's menu and navigation system. If you encounter any specific issues or need further customization, feel free to ask!