class home(APIView): #permissionclasses=[IsAuthenticated]…
- User
class home(APIView): #permission_classes=[IsAuthenticated] #permission_classes=[IsAuthenticated]
def get(self,request): catergories=Category.objects.all() catergoryserializedata=categoryserializer(catergories, many=True) #code to popular food items Popularfooditems=[] PopularFooditemreview=Review.objects.filter(review__gte=2)[0:3] for eachreview in PopularFooditemreview: fooditemserializeddata=foodserializer(eachreview.food_item) Popularfooditems.append(fooditemserializeddata.data) return Response({ 'categories':catergoryserializedata.data, 'popularitems':Popularfooditems },status=status.HTTP_200_OK)class displayCategories(APIView): permission_classes=[IsAuthenticated] def get(self,request,category_name): category=Category.objects.filter(category_name=category_name).first() Categoryfooditems=FoodItem.objects.filter(category=category) Categoryfooditemsserializedata=foodserializer(Categoryfooditems, many=True) return Response({ 'categoryfooditems':Categoryfooditemsserializedata.data })
class review(APIView): permission_classes=[IsAuthenticated]
def post(self,request,item_name): User=request.user food_item=FoodItem.objects.get(item_name=item_name) data=request.data.copy() data['food_item']=food_item.id data['person']=User.id serialized_review=ReviewSerializer(data=data) if serialized_review.is_valid(): serialized_review.save() return Response({ 'data_submission':'success' }) def get(self,request,item_name): user=request.user food_item=FoodItem.objects.get(item_name=item_name) if Review.objects.filter(food_item=food_item).exists(): review=Review.objects.filter(food_item=food_item) serialized_review=ReviewSerializer(review, many=True) return Response({ 'reviews':serialized_review.data, }) else: return Response({ 'empty':'no reviews' },status=status.HTTP_404_NOT_FOUND)this is the backend api i need to use it in my expo project here is the code i am using typescrypt import React, { useState, useEffect } from 'react'; import { View, Text, Image, ScrollView, TextInput, TouchableOpacity, StyleSheet } from 'react-native'; import { FontAwesome } from '@expo/vector-icons'; import axios from 'axios';
// Define types for Category and PopularItem interface Category { category_name: string; category_img: string; }
interface PopularItem { name: string; image: string; price: number; }
const FoodOrderingApp = () => { // Use the defined types when initializing the state const [categories, setCategories] = useState<Category[]>([]); const [popularItems, setPopularItems] = useState<PopularItem[]>([]);
useEffect(() => { fetchData(); }, []);
const fetchData = async () => { try { const response = await axios.get('https://yourapiurl.com/api/home/'); const data = response.data; setCategories(data.categories); // Update categories state setPopularItems(data.popularitems); // Update popular items state } catch (error) { console.error('Error fetching data:', error); } };
return ( {/* Header */} Menu
{/* Search Bar */} <View style={styles.searchContainer}> <TextInput style={styles.searchInput} placeholder="Search" placeholderTextColor="#000" /> </View> {/* Food Categories */} <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.categoriesContainer}> {categories.map((category, index) => ( <View key={index} style={styles.categoryItem}> <Image source={{ uri: https://yourapiurl.com/${category.category_img} }} // Display category image style={styles.categoryImage} /> <Text style={styles.categoryName}>{category.category_name}</Text> {/* Display category name */} </View> ))} </ScrollView> {/* Specials */} <View style={styles.specialsContainer}> <Text style={styles.specialsTitle}>Specials</Text> <View style={styles.specialsBox}> <Text style={styles.specialsTextBold}>flat</Text> <Text style={[styles.specialsTextBold, styles.specialsDiscount]}>50% OFF</Text> <Text style={styles.specialsText}>Combo Pack of the day</Text> </View> </View> {/* Popular Items */} <ScrollView style={styles.popularContainer}> <Text style={styles.popularTitle}>Popular</Text> <View style={styles.popularGrid}> {popularItems.map((item, index) => ( <View key={index} style={styles.popularItem}> <Image source={{ uri: item.image || '/api/placeholder/100/100' }} // Display food item image style={styles.popularImage} /> <Text style={styles.popularName}>{item.name}</Text> {/* Display food item name */} <View style={styles.popularFooter}> <Text style={styles.popularPrice}>₹ {item.price}</Text> {/* Display food item price */} <TouchableOpacity style={styles.addButton}> <Text style={styles.addButtonText}>+</Text> </TouchableOpacity> </View> </View> ))} </View> </ScrollView> {/* Bottom Navigation */} <View style={styles.bottomNav}> <TouchableOpacity> <FontAwesome name="home" size={24} color="black" /> </TouchableOpacity> <TouchableOpacity> <FontAwesome name="search" size={24} color="black" /> </TouchableOpacity> <TouchableOpacity> <FontAwesome name="shopping-cart" size={24} color="black" /> </TouchableOpacity> <TouchableOpacity> <FontAwesome name="user" size={24} color="black" /> </TouchableOpacity> </View> </View>); };
const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#6B46C1', }, header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 16, }, title: { fontSize: 24, fontWeight: 'bold', color: 'white', }, searchContainer: { paddingHorizontal: 16, marginBottom: 16, }, searchInput: { backgroundColor: 'white', borderRadius: 8, padding: 10, fontSize: 16, }, categoriesContainer: { flexDirection: 'row', paddingHorizontal: 16, marginBottom: 16, }, categoryItem: { alignItems: 'center', marginRight: 16, }, categoryImage: { width: 64, height: 64, borderRadius: 32, backgroundColor: 'red', }, categoryName: { color: 'white', marginTop: 8, fontSize: 14, }, specialsContainer: { backgroundColor: '#553C9A', padding: 16, marginBottom: 16, }, specialsTitle: { fontSize: 18, fontWeight: 'bold', color: 'white', marginBottom: 8, }, specialsBox: { backgroundColor: '#44337A', padding: 16, borderRadius: 8, }, specialsTextBold: { fontSize: 20, fontWeight: 'bold', color: 'white', }, specialsDiscount: { fontSize: 24, }, specialsText: { color: 'white', }, popularContainer: { flex: 1, paddingHorizontal: 16, }, popularTitle: { fontSize: 18, fontWeight: 'bold', color: 'white', marginBottom: 16, }, popularGrid: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between', }, popularItem: { backgroundColor: '#E53E3E', width: '48%', padding: 8, borderRadius: 8, marginBottom: 16, }, popularImage: { width: '100%', height: 100, borderRadius: 8, marginBottom: 8, }, popularName: { color: 'white', fontWeight: 'bold', }, popularFooter: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 8, }, popularPrice: { color: 'white', }, addButton: { backgroundColor: '#38A169', borderRadius: 4, padding: 4, }, addButtonText: { color: 'white', fontWeight: 'bold', }, bottomNav: { flexDirection: 'row', justifyContent: 'space-between', padding: 16, backgroundColor: '#E2E8F0', }, });
export default FoodOrderingApp;
write the complete code - Assistant
Certainly! Below is a comprehensive guide to building your Expo React Native app that interacts with your Django backend API. This guide covers:
- Project Setup
- Configuration of Axios for API Requests
- Authentication Flow (Login & Signup)
- Home Screen (Displaying Categories and Popular Items)
- Category Screen (Displaying Food Items in a Category)
- Review Screen (Displaying and Submitting Reviews)
- Navigation Setup
- Styling
Let's go through each step in detail.
1. Project Setup
First, ensure you have Node.js and Expo CLI installed. If not, install them:
npm install -g expo-cliInitialize a new Expo project with TypeScript:
expo init FoodOrderingApp --template expo-template-blank-typescript cd FoodOrderingAppInstall necessary dependencies:
npm install axios @react-navigation/native @react-navigation/stack @react-native-async-storage/async-storage @react-navigation/bottom-tabs @react-navigation/native-stack npm install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-masked-view/masked-viewNote: For React Navigation, additional steps might be required. Follow the official installation guide if you encounter issues.
2. Configuration of Axios for API Requests
Create a
servicesdirectory to manage API interactions.services/api.ts// services/api.ts import axios from 'axios'; import AsyncStorage from '@react-native-async-storage/async-storage'; // Create an instance of axios const api = axios.create({ baseURL: 'https://yourapiurl.com/api/', // Replace with your actual API base URL }); // Add a request interceptor to include the token in headers api.interceptors.request.use( async (config) => { const token = await AsyncStorage.getItem('token'); // Retrieve token from storage if (token) { config.headers.Authorization = `Bearer ${token}`; // Set the Authorization header } return config; }, (error) => { return Promise.reject(error); } ); export default api;
3. Authentication Flow (Login & Signup)
Implement authentication screens to handle user login and registration.
3.1. Create Authentication Context
Create a context to manage authentication state across the app.
contexts/AuthContext.tsx// contexts/AuthContext.tsx import React, { createContext, useState, useEffect } from 'react'; import { Alert } from 'react-native'; import AsyncStorage from '@react-native-async-storage/async-storage'; import api from '../services/api'; interface AuthContextProps { user: any; isLoading: boolean; login: (email: string, password: string) => Promise<void>; signup: (email: string, password: string) => Promise<void>; logout: () => void; } export const AuthContext = createContext<AuthContextProps>({ user: null, isLoading: false, login: async () => {}, signup: async () => {}, logout: () => {}, }); export const AuthProvider: React.FC = ({ children }) => { const [user, setUser] = useState<any>(null); const [isLoading, setIsLoading] = useState<boolean>(true); useEffect(() => { const loadUser = async () => { try { const token = await AsyncStorage.getItem('token'); if (token) { // Optionally, verify token validity by making a test API call setUser({ token }); } } catch (error) { console.log('Error loading user:', error); } finally { setIsLoading(false); } }; loadUser(); }, []); const login = async (email: string, password: string) => { try { const response = await api.post('login/', { email, password }); // Adjust endpoint as per your backend const { token, user } = response.data; await AsyncStorage.setItem('token', token); setUser(user); } catch (error: any) { console.log('Login error:', error); Alert.alert('Login Failed', error.response?.data?.message || 'An error occurred during login.'); } }; const signup = async (email: string, password: string) => { try { const response = await api.post('signup/', { email, password }); // Adjust endpoint as per your backend const { token, user } = response.data; await AsyncStorage.setItem('token', token); setUser(user); } catch (error: any) { console.log('Signup error:', error); Alert.alert('Signup Failed', error.response?.data?.message || 'An error occurred during signup.'); } }; const logout = async () => { await AsyncStorage.removeItem('token'); setUser(null); }; return ( <AuthContext.Provider value={{ user, isLoading, login, signup, logout }}> {children} </AuthContext.Provider> ); };3.2. Create Login Screen
screens/LoginScreen.tsx// screens/LoginScreen.tsx import React, { useState, useContext } from 'react'; import { View, Text, TextInput, TouchableOpacity, StyleSheet, ActivityIndicator, Alert } from 'react-native'; import { AuthContext } from '../contexts/AuthContext'; const LoginScreen: React.FC = ({ navigation }: any) => { const { login } = useContext(AuthContext); const [email, setEmail] = useState<string>(''); const [password, setPassword] = useState<string>(''); const [loading, setLoading] = useState<boolean>(false); const handleLogin = async () => { setLoading(true); if (!email || !password) { Alert.alert('Error', 'Please enter both email and password.'); setLoading(false); return; } await login(email, password); setLoading(false); }; return ( <View style={styles.container}> <Text style={styles.title}>Login</Text> <TextInput style={styles.input} placeholder="Email" placeholderTextColor="#666" autoCapitalize="none" keyboardType="email-address" value={email} onChangeText={(text) => setEmail(text)} /> <TextInput style={styles.input} placeholder="Password" placeholderTextColor="#666" secureTextEntry value={password} onChangeText={(text) => setPassword(text)} /> <TouchableOpacity style={styles.button} onPress={handleLogin} disabled={loading}> {loading ? <ActivityIndicator color="#fff" /> : <Text style={styles.buttonText}>Login</Text>} </TouchableOpacity> <TouchableOpacity onPress={() => navigation.navigate('Signup')}> <Text style={styles.link}>Don't have an account? Sign up</Text> </TouchableOpacity> </View> ); }; export default LoginScreen; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#6B46C1', alignItems: 'center', justifyContent: 'center', paddingHorizontal: 32, }, title: { fontSize: 32, color: 'white', marginBottom: 32, fontWeight: 'bold', }, input: { width: '100%', backgroundColor: 'white', padding: 12, borderRadius: 8, marginBottom: 16, }, button: { width: '100%', backgroundColor: '#553C9A', padding: 16, borderRadius: 8, alignItems: 'center', marginBottom: 16, }, buttonText: { color: 'white', fontWeight: 'bold', }, link: { color: 'white', textDecorationLine: 'underline', }, });3.3. Create Signup Screen
screens/SignupScreen.tsx// screens/SignupScreen.tsx import React, { useState, useContext } from 'react'; import { View, Text, TextInput, TouchableOpacity, StyleSheet, ActivityIndicator, Alert } from 'react-native'; import { AuthContext } from '../contexts/AuthContext'; const SignupScreen: React.FC = ({ navigation }: any) => { const { signup } = useContext(AuthContext); const [email, setEmail] = useState<string>(''); const [password, setPassword] = useState<string>(''); const [confirmPassword, setConfirmPassword] = useState<string>(''); const [loading, setLoading] = useState<boolean>(false); const handleSignup = async () => { setLoading(true); if (!email || !password || !confirmPassword) { Alert.alert('Error', 'Please fill all fields.'); setLoading(false); return; } if (password !== confirmPassword) { Alert.alert('Error', 'Passwords do not match.'); setLoading(false); return; } await signup(email, password); setLoading(false); }; return ( <View style={styles.container}> <Text style={styles.title}>Signup</Text> <TextInput style={styles.input} placeholder="Email" placeholderTextColor="#666" autoCapitalize="none" keyboardType="email-address" value={email} onChangeText={(text) => setEmail(text)} /> <TextInput style={styles.input} placeholder="Password" placeholderTextColor="#666" secureTextEntry value={password} onChangeText={(text) => setPassword(text)} /> <TextInput style={styles.input} placeholder="Confirm Password" placeholderTextColor="#666" secureTextEntry value={confirmPassword} onChangeText={(text) => setConfirmPassword(text)} /> <TouchableOpacity style={styles.button} onPress={handleSignup} disabled={loading}> {loading ? <ActivityIndicator color="#fff" /> : <Text style={styles.buttonText}>Signup</Text>} </TouchableOpacity> <TouchableOpacity onPress={() => navigation.navigate('Login')}> <Text style={styles.link}>Already have an account? Login</Text> </TouchableOpacity> </View> ); }; export default SignupScreen; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#6B46C1', alignItems: 'center', justifyContent: 'center', paddingHorizontal: 32, }, title: { fontSize: 32, color: 'white', marginBottom: 32, fontWeight: 'bold', }, input: { width: '100%', backgroundColor: 'white', padding: 12, borderRadius: 8, marginBottom: 16, }, button: { width: '100%', backgroundColor: '#553C9A', padding: 16, borderRadius: 8, alignItems: 'center', marginBottom: 16, }, buttonText: { color: 'white', fontWeight: 'bold', }, link: { color: 'white', textDecorationLine: 'underline', }, });
4. Home Screen (Displaying Categories and Popular Items)
Implement the Home screen to fetch and display categories and popular items.
screens/HomeScreen.tsx// screens/HomeScreen.tsx import React, { useState, useEffect } from 'react'; import { View, Text, Image, ScrollView, TextInput, TouchableOpacity, StyleSheet, ActivityIndicator } from 'react-native'; import { FontAwesome } from '@expo/vector-icons'; import api from '../services/api'; import { useNavigation } from '@react-navigation/native'; // Define types for Category and PopularItem interface Category { id: number; category_name: string; category_img: string; } interface PopularItem { id: number; name: string; image: string; price: number; } const HomeScreen: React.FC = () => { const [categories, setCategories] = useState<Category[]>([]); const [popularItems, setPopularItems] = useState<PopularItem[]>([]); const [loading, setLoading] = useState<boolean>(false); const navigation = useNavigation<any>(); useEffect(() => { fetchData(); }, []); const fetchData = async () => { setLoading(true); try { const response = await api.get('home/'); const data = response.data; setCategories(data.categories); // Update categories state setPopularItems(data.popularitems); // Update popular items state } catch (error) { console.error('Error fetching data:', error); } setLoading(false); }; const handleCategoryPress = (categoryName: string) => { navigation.navigate('Category', { categoryName }); }; const handlePopularItemPress = (itemName: string) => { navigation.navigate('Review', { itemName }); }; return ( <View style={styles.container}> {/* Header */} <View style={styles.header}> <Text style={styles.title}>Menu</Text> <TouchableOpacity onPress={() => navigation.navigate('Profile')}> <FontAwesome name="user" size={24} color="white" /> </TouchableOpacity> </View> {/* Search Bar */} <View style={styles.searchContainer}> <TextInput style={styles.searchInput} placeholder="Search" placeholderTextColor="#000" /> </View> {/* Food Categories */} <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.categoriesContainer}> {loading ? ( <ActivityIndicator color="white" /> ) : ( categories.map((category) => ( <TouchableOpacity key={category.id} style={styles.categoryItem} onPress={() => handleCategoryPress(category.category_name)}> <Image source={{ uri: `https://yourapiurl.com/${category.category_img}` }} // Replace with your actual image URL style={styles.categoryImage} /> <Text style={styles.categoryName}>{category.category_name}</Text> </TouchableOpacity> )) )} </ScrollView> {/* Specials */} <View style={styles.specialsContainer}> <Text style={styles.specialsTitle}>Specials</Text> <View style={styles.specialsBox}> <Text style={styles.specialsTextBold}>Flat</Text> <Text style={[styles.specialsTextBold, styles.specialsDiscount]}>50% OFF</Text> <Text style={styles.specialsText}>Combo Pack of the day</Text> </View> </View> {/* Popular Items */} <ScrollView style={styles.popularContainer}> <Text style={styles.popularTitle}>Popular</Text> <View style={styles.popularGrid}> {loading ? ( <ActivityIndicator color="white" /> ) : ( popularItems.map((item) => ( <TouchableOpacity key={item.id} style={styles.popularItem} onPress={() => handlePopularItemPress(item.name)}> <Image source={{ uri: `https://yourapiurl.com/${item.image}` || 'https://via.placeholder.com/100' }} // Replace with your actual image URL or placeholder style={styles.popularImage} /> <Text style={styles.popularName}>{item.name}</Text> <View style={styles.popularFooter}> <Text style={styles.popularPrice}>₹ {item.price}</Text> <TouchableOpacity style={styles.addButton}> <Text style={styles.addButtonText}>+</Text> </TouchableOpacity> </View> </TouchableOpacity> )) )} </View> </ScrollView> {/* Bottom Navigation */} {/* You can implement a bottom tab navigator instead */} </View> ); }; export default HomeScreen; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#6B46C1', paddingTop: 40, }, header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginHorizontal: 16, marginBottom: 16, }, title: { fontSize: 24, fontWeight: 'bold', color: 'white', }, searchContainer: { paddingHorizontal: 16, marginBottom: 16, }, searchInput: { backgroundColor: 'white', borderRadius: 8, padding: 10, fontSize: 16, }, categoriesContainer: { flexDirection: 'row', paddingHorizontal: 16, marginBottom: 16, }, categoryItem: { alignItems: 'center', marginRight: 16, }, categoryImage: { width: 64, height: 64, borderRadius: 32, backgroundColor: 'red', }, categoryName: { color: 'white', marginTop: 8, fontSize: 14, }, specialsContainer: { backgroundColor: '#553C9A', padding: 16, marginHorizontal: 16, borderRadius: 8, marginBottom: 16, }, specialsTitle: { fontSize: 18, fontWeight: 'bold', color: 'white', marginBottom: 8, }, specialsBox: { backgroundColor: '#44337A', padding: 16, borderRadius: 8, }, specialsTextBold: { fontSize: 20, fontWeight: 'bold', color: 'white', }, specialsDiscount: { fontSize: 24, }, specialsText: { color: 'white', }, popularContainer: { flex: 1, paddingHorizontal: 16, }, popularTitle: { fontSize: 18, fontWeight: 'bold', color: 'white', marginBottom: 16, }, popularGrid: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between', }, popularItem: { backgroundColor: '#E53E3E', width: '48%', padding: 8, borderRadius: 8, marginBottom: 16, }, popularImage: { width: '100%', height: 100, borderRadius: 8, marginBottom: 8, }, popularName: { color: 'white', fontWeight: 'bold', }, popularFooter: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 8, }, popularPrice: { color: 'white', }, addButton: { backgroundColor: '#38A169', borderRadius: 4, padding: 4, }, addButtonText: { color: 'white', fontWeight: 'bold', }, });Notes:
- Image URLs: Replace
https://yourapiurl.com/with your actual API's base URL. Ensure that the image paths returned by the API are correctly appended to form valid URLs. - Navigation: The
handleCategoryPressandhandlePopularItemPressfunctions navigate to respective screens. Ensure these screens are set up in your navigation stack.
5. Category Screen (Displaying Food Items in a Category)
Implement the Category screen to display food items within a selected category.
screens/CategoryScreen.tsx// screens/CategoryScreen.tsx import React, { useState, useEffect } from 'react'; import { View, Text, Image, ScrollView, TouchableOpacity, StyleSheet, ActivityIndicator } from 'react-native'; import api from '../services/api'; import { useRoute, useNavigation } from '@react-navigation/native'; interface FoodItem { id: number; name: string; image: string; price: number; } const CategoryScreen: React.FC = () => { const route = useRoute<any>(); const navigation = useNavigation<any>(); const { categoryName } = route.params; const [foodItems, setFoodItems] = useState<FoodItem[]>([]); const [loading, setLoading] = useState<boolean>(false); useEffect(() => { fetchCategoryFoodItems(); }, []); const fetchCategoryFoodItems = async () => { setLoading(true); try { const response = await api.get(`displayCategories/${categoryName}/`); const data = response.data; setFoodItems(data.categoryfooditems); } catch (error) { console.error('Error fetching category food items:', error); } setLoading(false); }; const handleFoodItemPress = (itemName: string) => { navigation.navigate('Review', { itemName }); }; return ( <View style={styles.container}> <Text style={styles.title}>{categoryName}</Text> {loading ? ( <ActivityIndicator color="white" /> ) : ( <ScrollView contentContainerStyle={styles.foodItemsContainer}> {foodItems.map((item) => ( <TouchableOpacity key={item.id} style={styles.foodItem} onPress={() => handleFoodItemPress(item.name)}> <Image source={{ uri: `https://yourapiurl.com/${item.image}` || 'https://via.placeholder.com/100' }} style={styles.foodImage} /> <View style={styles.foodInfo}> <Text style={styles.foodName}>{item.name}</Text> <Text style={styles.foodPrice}>₹ {item.price}</Text> </View> </TouchableOpacity> ))} </ScrollView> )} </View> ); }; export default CategoryScreen; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#6B46C1', paddingTop: 40, paddingHorizontal: 16, }, title: { fontSize: 24, color: 'white', fontWeight: 'bold', marginBottom: 16, textAlign: 'center', }, foodItemsContainer: { paddingBottom: 16, }, foodItem: { flexDirection: 'row', backgroundColor: '#553C9A', borderRadius: 8, padding: 12, marginBottom: 12, alignItems: 'center', }, foodImage: { width: 64, height: 64, borderRadius: 8, marginRight: 12, }, foodInfo: { flex: 1, }, foodName: { color: 'white', fontSize: 16, fontWeight: 'bold', }, foodPrice: { color: 'white', marginTop: 4, }, });
6. Review Screen (Displaying and Submitting Reviews)
Implement the Review screen to display existing reviews and allow users to submit new ones.
screens/ReviewScreen.tsx// screens/ReviewScreen.tsx import React, { useState, useEffect, useContext } from 'react'; import { View, Text, TextInput, TouchableOpacity, StyleSheet, ActivityIndicator, FlatList, Alert } from 'react-native'; import api from '../services/api'; import { useRoute } from '@react-navigation/native'; import { AuthContext } from '../contexts/AuthContext'; interface Review { id: number; rating: number; comment: string; person: { id: number; email: string; }; } const ReviewScreen: React.FC = () => { const route = useRoute<any>(); const { itemName } = route.params; const { user } = useContext(AuthContext); const [reviews, setReviews] = useState<Review[]>([]); const [loading, setLoading] = useState<boolean>(false); const [rating, setRating] = useState<string>(''); const [comment, setComment] = useState<string>(''); const [submitting, setSubmitting] = useState<boolean>(false); useEffect(() => { fetchReviews(); }, []); const fetchReviews = async () => { setLoading(true); try { const response = await api.get(`review/${itemName}/`); const data = response.data; setReviews(data.reviews); } catch (error) { console.error('Error fetching reviews:', error); } setLoading(false); }; const submitReview = async () => { if (!rating || !comment) { Alert.alert('Error', 'Please enter both rating and comment.'); return; } const ratingNumber = parseInt(rating); if (isNaN(ratingNumber) || ratingNumber < 1 || ratingNumber > 5) { Alert.alert('Error', 'Rating must be a number between 1 and 5.'); return; } setSubmitting(true); try { const response = await api.post(`review/${itemName}/`, { review: ratingNumber, comment, }); if (response.data.data_submission === 'success') { Alert.alert('Success', 'Review submitted successfully.'); setRating(''); setComment(''); fetchReviews(); // Refresh reviews } } catch (error: any) { console.error('Error submitting review:', error); Alert.alert('Error', error.response?.data?.message || 'Failed to submit review.'); } setSubmitting(false); }; const renderReview = ({ item }: { item: Review }) => ( <View style={styles.reviewItem}> <Text style={styles.reviewUser}>{item.person.email}</Text> <Text style={styles.reviewRating}>Rating: {item.rating}/5</Text> <Text style={styles.reviewComment}>{item.comment}</Text> </View> ); return ( <View style={styles.container}> <Text style={styles.title}>Reviews for {itemName}</Text> {loading ? ( <ActivityIndicator color="white" /> ) : ( <FlatList data={reviews} keyExtractor={(item) => item.id.toString()} renderItem={renderReview} contentContainerStyle={styles.reviewList} ListEmptyComponent={<Text style={styles.noReviews}>No reviews yet.</Text>} /> )} <View style={styles.submitContainer}> <Text style={styles.submitTitle}>Submit a Review</Text> <TextInput style={styles.input} placeholder="Rating (1-5)" placeholderTextColor="#666" keyboardType="numeric" value={rating} onChangeText={(text) => setRating(text)} /> <TextInput style={[styles.input, styles.commentInput]} placeholder="Comment" placeholderTextColor="#666" multiline numberOfLines={4} value={comment} onChangeText={(text) => setComment(text)} /> <TouchableOpacity style={styles.button} onPress={submitReview} disabled={submitting}> {submitting ? <ActivityIndicator color="#fff" /> : <Text style={styles.buttonText}>Submit</Text>} </TouchableOpacity> </View> </View> ); }; export default ReviewScreen; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#6B46C1', paddingTop: 40, paddingHorizontal: 16, }, title: { fontSize: 24, color: 'white', fontWeight: 'bold', marginBottom: 16, textAlign: 'center', }, reviewList: { paddingBottom: 16, }, reviewItem: { backgroundColor: '#553C9A', padding: 12, borderRadius: 8, marginBottom: 12, }, reviewUser: { color: 'white', fontWeight: 'bold', marginBottom: 4, }, reviewRating: { color: 'white', marginBottom: 4, }, reviewComment: { color: 'white', }, noReviews: { color: 'white', textAlign: 'center', marginTop: 16, }, submitContainer: { backgroundColor: '#44337A', padding: 16, borderRadius: 8, marginTop: 16, }, submitTitle: { color: 'white', fontSize: 18, fontWeight: 'bold', marginBottom: 8, }, input: { backgroundColor: 'white', borderRadius: 8, padding: 10, fontSize: 16, marginBottom: 12, }, commentInput: { height: 80, textAlignVertical: 'top', }, button: { backgroundColor: '#38A169', padding: 16, borderRadius: 8, alignItems: 'center', }, buttonText: { color: 'white', fontWeight: 'bold', }, });
7. Navigation Setup
Set up navigation to handle screen transitions.
App.tsx// App.tsx import React from 'react'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import { AuthProvider, AuthContext } from './contexts/AuthContext'; import LoginScreen from './screens/LoginScreen'; import SignupScreen from './screens/SignupScreen'; import HomeScreen from './screens/HomeScreen'; import CategoryScreen from './screens/CategoryScreen'; import ReviewScreen from './screens/ReviewScreen'; const Stack = createStackNavigator(); const App: React.FC = () => { return ( <AuthProvider> <NavigationContainer> <AuthContext.Consumer> {({ user, isLoading }) => isLoading ? ( // Optionally, display a splash screen or loader null ) : user ? ( <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} options={{ headerShown: false }} /> <Stack.Screen name="Category" component={CategoryScreen} options={{ headerShown: false }} /> <Stack.Screen name="Review" component={ReviewScreen} options={{ headerShown: false }} /> {/* Add more screens as needed */} </Stack.Navigator> ) : ( <Stack.Navigator> <Stack.Screen name="Login" component={LoginScreen} options={{ headerShown: false }} /> <Stack.Screen name="Signup" component={SignupScreen} options={{ headerShown: false }} /> </Stack.Navigator> ) } </AuthContext.Consumer> </NavigationContainer> </AuthProvider> ); }; export default App;Explanation:
- AuthProvider: Wraps the entire app to provide authentication state.
- AuthContext.Consumer: Determines whether the user is logged in and navigates accordingly.
- Stack Navigator: Manages navigation between screens.
8. Styling
The styles have been included within each screen's component using
StyleSheet. However, for better scalability and reusability, consider abstracting common styles or using a theme.
9. Additional Considerations
9.1. Profile Screen
You might want to implement a Profile screen where users can see their information and logout.
screens/ProfileScreen.tsx// screens/ProfileScreen.tsx import React, { useContext } from 'react'; import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'; import { AuthContext } from '../contexts/AuthContext'; const ProfileScreen: React.FC = () => { const { user, logout } = useContext(AuthContext); return ( <View style={styles.container}> <Text style={styles.title}>Profile</Text> {/* Display user information */} <Text style={styles.info}>Email: {user.email}</Text> {/* Add more user info as needed */} <TouchableOpacity style={styles.button} onPress={logout}> <Text style={styles.buttonText}>Logout</Text> </TouchableOpacity> </View> ); }; export default ProfileScreen; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#6B46C1', alignItems: 'center', justifyContent: 'center', paddingHorizontal: 32, }, title: { fontSize: 32, color: 'white', marginBottom: 32, fontWeight: 'bold', }, info: { color: 'white', fontSize: 18, marginBottom: 16, }, button: { backgroundColor: '#E53E3E', padding: 16, borderRadius: 8, width: '100%', alignItems: 'center', marginTop: 16, }, buttonText: { color: 'white', fontWeight: 'bold', }, });Update Navigation to Include Profile Screen
Modify
App.tsxto include the Profile screen in the stack.// Inside App.tsx Stack.Navigator for logged-in users <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} options={{ headerShown: false }} /> <Stack.Screen name="Category" component={CategoryScreen} options={{ headerShown: false }} /> <Stack.Screen name="Review" component={ReviewScreen} options={{ headerShown: false }} /> <Stack.Screen name="Profile" component={ProfileScreen} options={{ headerShown: false }} /> {/* Add more screens as needed */} </Stack.Navigator>9.2. Handling Token Expiry
Implement logic to handle token expiration and refresh tokens if your backend supports it.
9.3. Error Handling
Ensure comprehensive error handling across all API interactions to provide feedback to users.
9.4. Secure Storage
Consider using more secure storage solutions for tokens, such as
expo-secure-store, especially for sensitive applications.9.5. Optimizations
- Caching: Implement caching strategies for API responses to reduce redundant network calls.
- State Management: For larger applications, consider using state management libraries like Redux or Zustand.
10. Final Project Structure
Your project should resemble the following structure:
FoodOrderingApp/ ├── App.tsx ├── assets/ │ └── ... // Your assets ├── babel.config.js ├── package.json ├── services/ │ └── api.ts ├── contexts/ │ └── AuthContext.tsx ├── screens/ │ ├── HomeScreen.tsx │ ├── LoginScreen.tsx │ ├── SignupScreen.tsx │ ├── CategoryScreen.tsx │ ├── ReviewScreen.tsx │ └── ProfileScreen.tsx ├── tsconfig.json └── ... // Other configuration files
Conclusion
This guide provides a complete setup for your Expo React Native project interacting with your Django backend API. It includes user authentication, data fetching, and navigation between different screens. Customize and expand upon this foundation based on your specific requirements.
Remember to:
- Replace placeholder URLs (
https://yourapiurl.com/) with your actual backend API URLs. - Adjust API endpoints (
login/,signup/, etc.) based on your Django backend configuration. - Handle image URLs correctly to ensure images are displayed properly.
- Secure your application by handling tokens securely and implementing necessary validations.
Feel free to reach out if you encounter any issues or need further assistance!