Skip to content

Commit

Permalink
storing the cart data in firestore (#64)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hemu21 authored May 11, 2024
1 parent 83f0551 commit 80a2c40
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 88 deletions.
27 changes: 27 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import AddProductForm from "./pages/AddProd";
// import data from './data';
import MapComponent from "./components/map/ITEMmap";
import SellerForm from "./pages/SellerRegistration";
import { db } from "./firebase";
import { collection, doc, getDocs } from "firebase/firestore";

const MyContext = createContext();

Expand All @@ -48,6 +50,29 @@ function App() {
const [isLogin, setIsLogin] = useState();
const [isOpenFilters, setIsopenFilters] = useState(false);
const [data, setData] = useState([]);
const [cartCount,setCartCount] = useState(0)


useEffect(()=>{
fetchCartProducts()
},[])

const fetchCartProducts = async () => {
try {
const cartRef = doc(db, 'carts', localStorage.getItem("uid"));
const productsCollectionRef = collection(cartRef, 'products');
const querySnapshot = await getDocs(productsCollectionRef);
const products = [];
querySnapshot.forEach((doc) => {
products.push({ id: doc.id, ...doc.data() });
});
setCartItems(products);
setCartCount(products.length); // Set the product count
} catch (error) {
console.error('Error fetching cart products:', error);
}
};


useEffect(() => {
const fetchData = async () => {
Expand Down Expand Up @@ -184,6 +209,8 @@ function App() {
openFilters,
isopenNavigation,
setIsopenNavigation,
cartCount,
setCartCount
};

return data && data.productData ? (
Expand Down
32 changes: 1 addition & 31 deletions src/components/header/header.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ const Header = (props) => {
const [windowWidth, setWindowWidth] = useState(window.innerWidth);
const [isopenSearch, setOpenSearch] = useState(false);
const [isOpenNav, setIsOpenNav] = useState(false);
const [cartCount, setCartCount] = useState(0);

const {cartCount, setCartCount} = useContext(MyContext);
const headerRef = useRef();
const searchInput = useRef();

Expand Down Expand Up @@ -96,35 +95,6 @@ const Header = (props) => {
// })
// }, [])

const getCartCount = () => {
try {
const db = getDatabase();
const dataRef = ref(db, `${localStorage.getItem("user")}`);

onValue(
dataRef,
(snapshot) => {
const data = snapshot.val();
if (data) {
const itemCount = Object.values(data).length;
setCartCount(itemCount);
} else {
setCartCount(0);
}
},
(error) => {
console.error("Error fetching data:", error);
}
);
} catch (error) {
console.error("Error:", error);
}
};

useEffect(() => {
getCartCount();
}, []);

const signOut = () => {
context.signOut();
history("/");
Expand Down
19 changes: 7 additions & 12 deletions src/components/product/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import RemoveRedEyeOutlinedIcon from '@mui/icons-material/RemoveRedEyeOutlined';
import { getDatabase, ref, onValue, set, push, child, remove } from "firebase/database";

import { MyContext } from '../../App';
import { db } from '../../firebase';
import { doc, setDoc } from 'firebase/firestore';


const Product = (props) => {
Expand Down Expand Up @@ -91,25 +93,18 @@ const Product = (props) => {
}
}, [userLocation, productData]);


const addToCart = async (item) => {
try {
const user=localStorage.getItem('user')
// Initialize Firebase database with the provided database URL
const db = getDatabase();
const cartRef = ref(db,user );
// Generate a unique key using the user's email and item details
const uniqueKey = user+item.id; // Modify as per your requirement
// Add item to the cart in Firebase
await set(child(cartRef, uniqueKey), { ...item, quantity: 1 });
const user=localStorage.getItem('uid')
const cartRef = doc(db, 'carts', user);
const productRef = doc(cartRef, 'products', `${item.id}`);
await setDoc(productRef, {...item, quantity: 1});
setIsadded(true)
// Assuming setIsAdded updates the state to indicate the item is added
//console.log('Item added to cart successfully');
context.setCartCount(context.cartCount+1);
} catch (error) {
console.error('Error adding item to cart:', error);
}
};

if(loading){
return <div>Loading...</div>
}
Expand Down
6 changes: 3 additions & 3 deletions src/pages/AddProd/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export default function AddProductForm() {

const addProd = async (main,sub) => { // funtion to add products data to firestore
try {
await addDoc(collection(db, 'sellers', `${localStorage.getItem("user")}_details`, 'products'), {
await addDoc(collection(db, 'sellers', localStorage.getItem("uid"), 'products'), {
productName: formData.productName,
price: formData.price,
discountPrice: formData.discountPrice,
Expand Down Expand Up @@ -70,12 +70,12 @@ export default function AddProductForm() {
const handleSubmit = async () => {
setIsSubmit(true)
//Upload the main image to firebase storage and get url
const imageRef = ref(storage, `productImages/${localStorage.getItem("user")}/${formData.productName}/mainImage`);
const imageRef = ref(storage, `productImages/${localStorage.getItem("uid")}/${formData.productName}/mainImage`);
await uploadBytes(imageRef, formData.mainImage);
const imageUrl = await getDownloadURL(imageRef);

//Upload the subsidiary image to firebase storage and get url
const imageRef1 = ref(storage, `productImages/${localStorage.getItem("user")}/${formData.productName}/subsidiaryImages`);
const imageRef1 = ref(storage, `productImages/${localStorage.getItem("uid")}/${formData.productName}/subsidiaryImages`);
await uploadBytes(imageRef1, formData.subsidiaryImages);
const imageUrl1 = await getDownloadURL(imageRef1);

Expand Down
47 changes: 9 additions & 38 deletions src/pages/Details/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import { MyContext } from '../../App';
import MapComponent from '../../components/map/ITEMmap';
import { Email } from '@mui/icons-material';
import useLoggedInUserEmail from '../../Hooks/useLoggedInUserEmail';
import { db } from '../../firebase';
import { doc, setDoc } from 'firebase/firestore';



Expand Down Expand Up @@ -255,51 +257,20 @@ const DetailsPage = (props) => {

}



// const addToCart = (item) => {
// context.addToCart(item);

// setIsadded(true);
// }
const addToCart = async (item) => {
try {
const user=localStorage.getItem('user')
// Initialize Firebase database with the provided database URL
const db = getDatabase();
const cartRef = ref(db,user );
// Generate a unique key using the user's email and item details
const uniqueKey = user+item.id; // Modify as per your requirement
// Add item to the cart in Firebase
await set(child(cartRef, uniqueKey), { ...item, quantity: 1 });
console.log("not global in comp prod index",item)
console.log(item.id)
const user=localStorage.getItem('uid')
const cartRef = doc(db, 'carts', user);
const productRef = doc(cartRef, 'products', `${item.id}`);
await setDoc(productRef, {...item, quantity: 1});
setIsadded(true)
// Assuming setIsAdded updates the state to indicate the item is added
//console.log('Item added to cart successfully');
context.setCartCount(context.cartCount+1);
} catch (error) {
console.error('Error adding item to cart:', error);
}
};
// Fetch data from Firebase Realtime Database
// const fetchDataFromFirebase = () => {
// try {
// // Get a reference to the database
// const db = getDatabase();

// // Reference to the node or path you want to fetch data from
// const dataRef = ref(db, localStorage.getItem('user'));

// // Fetch data from the specified path
// onValue(dataRef, (snapshot) => {
// const data = snapshot.val();
// //console.log("Data fetched successfully:", data);
// }, (error) => {
// console.error("Error fetching data:", error);
// });
// } catch (error) {
// console.error("Error:", error);
// }
// };


const getCartData = async (url) => {
try {
Expand Down
7 changes: 4 additions & 3 deletions src/pages/SellerRegistration/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ const SellerForm = () => {
const addUser = async (userId,photo) => { // funtion to add sellers data to firestore
try {
await setDoc(doc(db, "sellers", userId), {
uid: userId,
ownerName: formFields.ownerName,
phoneNumber: formFields.phoneNumber,
location: formFields.location,
Expand Down Expand Up @@ -98,10 +99,10 @@ const SellerForm = () => {
e.preventDefault();
setIsSubmit(true)
// Generate a unique key
const uniqueKey = `${localStorage.getItem("user")}_details`;
const uniqueKey = localStorage.getItem("uid");

//Upload the shop photo image to firebase storage and get url
const imageRef = ref(storage, `sellerImages/${localStorage.getItem("user")}/shopPhoto`);
const imageRef = ref(storage, `sellerImages/${localStorage.getItem("uid")}/shopPhoto`);
await uploadBytes(imageRef, formFields.shopPhoto);
const imageUrl = await getDownloadURL(imageRef);

Expand All @@ -112,7 +113,7 @@ const SellerForm = () => {
};

useEffect(()=>{
checkUserInSellers(`${localStorage.getItem("user")}_details`)
checkUserInSellers(localStorage.getItem("uid"))
},[])

return (
Expand Down
2 changes: 2 additions & 0 deletions src/pages/SignIn/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ const SignIn = () => {
context.signIn();
dispatch(logIn({email:user.email}))
setLoggedInUseEmail(user.email);
localStorage.setItem("uid", userCredential.user.uid);
//console.log(loggedInUserEmail);
history("/");
})
Expand All @@ -125,6 +126,7 @@ const SignIn = () => {
localStorage.setItem("isLogin", true);
const udata = replaceSpecialCharacters(result.user.email);
localStorage.setItem("user", udata);
localStorage.setItem("uid", result.user.uid);
context.signIn();
setLoggedInUseEmail(udata);
//console.log(loggedInUserEmail);
Expand Down
25 changes: 24 additions & 1 deletion src/pages/cart/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@ import { getDatabase, ref, onValue, remove } from "firebase/database";
import { useNavigate } from "react-router-dom";
import KeyboardBackspaceIcon from "@mui/icons-material/KeyboardBackspace";
import MapComponent from "../../components/map/ITEMmap";
import { db } from "../../firebase";
import { collection, doc, getDocs, onSnapshot } from "firebase/firestore";
const Cart = () => {
const [cartItems, setCartItems] = useState([]);
const [error, setError] = useState(null);
const [totalPrice, setTotalPrice] = useState(0);
const context = useContext(MyContext);
const navigate = useNavigate();

const [uid,setUid] = useState(localStorage.getItem("uid"))
useEffect(() => {
try {
if (context.isLogin === "true") {
Expand All @@ -38,6 +40,27 @@ const Cart = () => {
}
}, []);

useEffect(() => {
fetchCartProducts()
}, [db,uid]);

const fetchCartProducts = async () => {
try {
const cartRef = doc(db, 'carts', uid);
const productsCollectionRef = collection(cartRef, 'products');
const querySnapshot = await getDocs(productsCollectionRef);
const products = [];
querySnapshot.forEach((doc) => {
products.push({ id: doc.id, ...doc.data() });
});
console.log(products)
setCartItems(products);
} catch (error) {
console.error('Error fetching cart products:', error);
}
};


const getCartData = async () => {
try {
const db = getDatabase();
Expand Down

0 comments on commit 80a2c40

Please sign in to comment.