Today, you’ll create a User Profile screen to display user information and an Order History screen to show completed purchases. You’ll store each order in Firestore when the payment is completed, allowing users to view their purchase history.
What You Will Do Today:
- Create a User Profile screen to display user details.
- Implement order saving in Firestore after a successful payment.
- Create an Order History screen to display past orders.
Step 1: Setting Up User Profiles
- In
screens
, create a file calledUserProfile.js
.
// screens/UserProfile.js
import React, { useContext, useState, useEffect } from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import auth from '@react-native-firebase/auth';
function UserProfile({ navigation }) {
const [user, setUser] = useState(null);
useEffect(() => {
const currentUser = auth().currentUser;
setUser(currentUser);
}, []);
const handleSignOut = () => {
auth().signOut();
navigation.replace('LoginScreen');
};
return (
<View style={styles.container}>
<Text style={styles.title}>User Profile</Text>
{user ? (
<View>
<Text>Email: {user.email}</Text>
<Text>UID: {user.uid}</Text>
<Button title="Sign Out" onPress={handleSignOut} />
</View>
) : (
<Text>Loading user data...</Text>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 20,
},
});
export default UserProfile;
Step 2: Save Orders to Firestore After Successful Payment
- In
CheckoutScreen.js
, update the handlePay function to save the order to Firestore after a successful payment.
import firestore from '@react-native-firebase/firestore';
import auth from '@react-native-firebase/auth';
const handlePay = async () => {
const { error, paymentIntent } = await confirmPayment(clientSecret, {
type: 'Card',
billingDetails: { email: '[email protected]' },
});
if (error) {
Alert.alert('Payment failed', error.message);
} else if (paymentIntent) {
Alert.alert('Payment succeeded', 'Thank you for your purchase!');
// Save order details to Firestore
const order = {
userId: auth().currentUser.uid,
items: cart,
amount: cart.reduce((sum, item) => sum + item.price, 0),
createdAt: firestore.FieldValue.serverTimestamp(),
};
await firestore().collection('orders').add(order);
// Clear cart after successful payment
setCart([]);
await AsyncStorage.removeItem('cart');
navigation.navigate('OrderHistory');
}
};
Explanation of Code:
- order: An object containing the user ID, purchased items, total amount, and timestamp.
- The order is saved to Firestore in the
orders
collection for easy retrieval.
Step 3: Creating an Order History Screen
- In
screens
, create a file calledOrderHistory.js
.
// screens/OrderHistory.js
import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';
import firestore from '@react-native-firebase/firestore';
import auth from '@react-native-firebase/auth';
function OrderHistory() {
const [orders, setOrders] = useState([]);
useEffect(() => {
const fetchOrders = async () => {
const userId = auth().currentUser.uid;
const snapshot = await firestore()
.collection('orders')
.where('userId', '==', userId)
.orderBy('createdAt', 'desc')
.get();
const orderList = snapshot.docs.map(doc => ({
id: doc.id,
...doc.data(),
}));
setOrders(orderList);
};
fetchOrders();
}, []);
const renderOrder = ({ item }) => (
<View style={styles.orderItem}>
<Text style={styles.orderDate}>Order Date: {item.createdAt?.toDate().toDateString()}</Text>
<Text>Total Amount: ${item.amount.toFixed(2)}</Text>
<Text>Items:</Text>
{item.items.map((product, index) => (
<Text key={index} style={styles.productItem}>
- {product.name}: ${product.price.toFixed(2)}
</Text>
))}
</View>
);
return (
<View style={styles.container}>
<Text style={styles.title}>Order History</Text>
<FlatList
data={orders}
renderItem={renderOrder}
keyExtractor={(item) => item.id}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 16,
},
orderItem: {
padding: 16,
backgroundColor: '#f9f9f9',
borderRadius: 8,
marginVertical: 8,
borderWidth: 1,
borderColor: '#ddd',
},
orderDate: {
fontSize: 16,
fontWeight: 'bold',
marginBottom: 8,
},
productItem: {
fontSize: 14,
color: '#555',
},
});
export default OrderHistory;
Step 4: Adding Navigation to Profile and Order History
- Add UserProfile and OrderHistory screens to the navigation stack in
App.js
:
import UserProfile from './screens/UserProfile';
import OrderHistory from './screens/OrderHistory';
<Stack.Screen name="UserProfile" component={UserProfile} options={{ title: 'Profile' }} />
<Stack.Screen name="OrderHistory" component={OrderHistory} options={{ title: 'Order History' }} />
- In
ProductList
, add buttons to navigate to Profile and Order History:
<Button title="Profile" onPress={() => navigation.navigate('UserProfile')} />
<Button title="Order History" onPress={() => navigation.navigate('OrderHistory')} />
Step 5: Testing User Profiles and Order History
- Run the app with
npx react-native run-android
ornpx react-native run-ios
. - Complete a purchase to save an order.
- Navigate to the Order History screen to view the list of past orders.
- Go to the Profile screen to view user information.
Summary
Today, you added User Profile and Order History screens to your e-commerce app. Users can view their profile information and see a history of their purchases.
Tomorrow, you’ll secure your app by adding Firebase rules and authentication.