Sitemap

Building a User-Specific Cart Page in React

Creating a Dynamic Shopping Experience with Firebase and Chakra UI

--

Press enter or click to view image in full size
Photo by Campaign Creators on Unsplash

In today’s e-commerce landscape, delivering a seamless and dynamic shopping experience is essential. This article will walk you through the creation of a user-specific cart page using React, Firebase, and Chakra UI. The provided code snippet demonstrates how to fetch user-specific cart data from Firebase, display it in a visually appealing layout, and allow users to adjust item quantities or remove items. Let’s break down the core features of the code and understand how it works.

Core Features of the User-Specific Cart Page

  1. Fetching User Data from Local Storage: The component begins by retrieving the currently logged-in user’s ID from the browser’s local storage. This user ID is crucial for fetching the corresponding cart data from Firebase.
useEffect(() => {
const storedUser = JSON.parse(localStorage.getItem("currloginuser"));
if (storedUser && storedUser[0]) {
setUserId(storedUser[0][0]);
}
}, []);
// endponts

- user
- userId1
- emailId
- userName
- cart
- cart-item-1
- cart-item-2
.....

2. Retrieving Cart Items from Firebase: Once the user ID is obtained, the component makes an API call to Firebase to fetch the user’s cart items. The retrieved data is stored in the cartItems state.

useEffect(() => {
if (!userId) return;

const firebaseUrl = `https://name.firebasedatabase.app/user/${userId}/cart.json`;

axios
.get(firebaseUrl)
.then((response) => {
console.log("Retrieved data from Firebase:", response.data);
setCartItems(response.data || []);
})
.catch((error) => {
console.error("Error fetching data from Firebase:", error);
});
}, [userId]);

Get Everus Lainus’s stories in your inbox

Join Medium for free to get updates from this writer.

3. Calculating the Total Cost: The total cost of the cart is computed whenever the cartItems state changes. This calculation multiplies the price of each item by its quantity and sums up the results.

useEffect(() => {
const totalSum = cartItems.reduce(
(sum, item) => sum + item.price * item.quantity,
0
);
setTotal(totalSum);
}, [cartItems]);

4. Updating Item Quantities: The handleQuantityChange function allows users to increase or decrease the quantity of a specific item in their cart. The updated cart data is then sent back to Firebase to keep the backend in sync.

const handleQuantityChange = (index, change) => {
const updatedItems = [...cartItems];
updatedItems[index].quantity = Math.max(
1,
updatedItems[index].quantity + change
);
setCartItems(updatedItems);

if (userId) {
axios
.patch(
`https://name.firebasedatabase.app/user/${userId}.json`,
{ cart: updatedItems }
)
.then((response) => {
console.log("Cart updated in Firebase:", response.data);
})
.catch((error) => {
console.error("Error updating cart in Firebase:", error);
});
}
};

5. Removing Items from the Cart: Users can also remove items from their cart using the handleRemoveFromCart function. Similar to quantity updates, this function modifies the local state and sends the updated cart data to Firebase.

const handleRemoveFromCart = (index) => {
const updatedItems = [...cartItems];
updatedItems.splice(index, 1);
setCartItems(updatedItems);

if (userId) {
axios
.patch(
`https://name.firebasedatabase.app/user/${userId}.json`,
{ cart: updatedItems }
)
.then((response) => {
console.log("Cart updated in Firebase:", response.data);
})
.catch((error) => {
console.error("Error updating cart in Firebase:", error);
});
}
};

6. Displaying the Cart: The component renders the cart items dynamically using Chakra UI components, providing a clean and responsive design. Each cart item displays its image, name, price, and quantity, along with buttons to adjust the quantity or remove the item.

return (
<Box w="100%" className="backgroundchange">
<Box
padding="0px 30px"
backgroundColor="#303030"
maxWidth="1360px"
margin="0 auto"
borderRadius="md"
>
<Heading mb={6} color="white" textAlign="center">
Your Cart
</Heading>
{cartItems != null && cartItems.length > 0 ? (
<Flex direction={{ base: "column", lg: "row" }} gap="10px">
{/* Cart Items and Checkout Card Rendering */}
</Flex>
) : (
<Text color="white" textAlign="center">
Your cart is empty
</Text>
)}
</Box>
</Box>
);

Conclusion

By combining React’s state management with Firebase’s real-time database and the aesthetic appeal of Chakra UI, this code creates a robust and user-friendly cart page. The dynamic fetching and updating of user-specific data ensure a personalized shopping experience that enhances user engagement. This approach not only demonstrates how to manage user data effectively but also highlights the importance of creating a responsive and interactive user interface in modern web applications.

--

--