Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PR for the E-commerce App #1

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
16,259 changes: 16,259 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

44 changes: 44 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.

Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>FitKart</title>
</head>

<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.

You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.

To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
44 changes: 44 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import "./styles.css";
import { Route, Routes } from "react-router-dom";
import { useEffect } from "react";
import { Navbar } from "./components/navbar/navbar";
import { Products } from "./components/products/Products";
import { Cart } from "./components/cart/Cart";
import { Wishlist } from "./components/wishlist/Wishlist";
import { useData } from "./hooks/useData";
import { getCartAPICall, getWishlistAPICall } from "./apiCall";
import { Login } from "./components/login/Login";
import { Signup } from "./components/signup/Signup";
import { PrivateRoute } from "./components/privateRoute/PrivateRoute";
import { Orders } from "./components/orders/Orders";

export default function App() {
const { dispatch } = useData();
useEffect(() => {
(async () => {
const response = await getCartAPICall();
const cartItems = response.data.cartItems;
dispatch({ type: "INITIALIZE_CART", payload: { cartItems } });
})();
}, []);
useEffect(() => {
(async () => {
const response = await getWishlistAPICall();
const wishlistItems = response.data.wishlistItems;
dispatch({ type: "INITIALIZE_WISHLIST", payload: { wishlistItems } });
})();
}, []);
return (
<div className="App">
<Navbar />
<Routes>
<Route path="/" element={<Products />} />
<Route path="/login" element={<Login />} />
<Route path="/signup" element={<Signup/>} />
<PrivateRoute path="/wishlist" element={<Wishlist />} />
<PrivateRoute path="/cart" element={<Cart />} />
<PrivateRoute path="/orders" element={<Orders />} />
</Routes>
</div>
);
}
55 changes: 55 additions & 0 deletions src/apiCall.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import axios from "axios";

const baseURL = "https://fitkartapi.pranjalmahajan.repl.co";

export const getProductsAPICall = async () => {
const response = await axios.get(`${baseURL}/products`);
return response;
};

export const getWishlistAPICall = async () => {
const response = await axios.get(`${baseURL}/wishlist`);
return response;
};

export const getCartAPICall = async () => {
const response = await axios.get(`${baseURL}/cart`);
return response;
};

export const addItemToWishlistAPICall = async (_id) => {
const response = await axios.post(`${baseURL}/wishlist`, {
product: _id
});
return response;
};

export const addItemToCartAPICall = async (_id, q) => {
const response = await axios.post(`${baseURL}/cart`, {
product: _id,
qty: q
});
return response;
};

export const removeItemFromCartAPICall = async (_id) => {
const response = await axios.delete(`${baseURL}/cart/${_id}`);
return response;
}; // working => check id = id should be of the cart item and not the product id

export const removeItemFromWishlistAPICall = async (_id) => {
const response = await axios.delete(`${baseURL}/wishlist/${_id}`);
return response;
}; // working => check id = id should be of the wishlist item and not the product id

export const incQtyInCartAPICall = async (item) => {
const q = item.qty + 1;
const response = await axios.post(`${baseURL}/cart/${item._id}`, { qty: q });
return response;
};

export const decQtyInCartAPICall = async (item) => {
const q = item.qty - 1;
const response = await axios.post(`${baseURL}/cart/${item._id}`, { qty: q });
return response;
};
58 changes: 58 additions & 0 deletions src/components/cart/Cart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { useEffect, useState } from "react";
import { useData } from "../../hooks/useData";
import { CartEmpty } from "./CartEmpty";
import { CartCard } from "./CartCard";
import { CartTotal } from "./CartTotal";
import { ToastContainer } from "react-toastify";
import { getCartAPICall } from "../../apiCall";
import { Loader } from "../loader/Loader";

export const Cart = () => {
const { dispatch } = useData();
const { itemsInCart } = useData();
const [showLoader, setShowLoader] = useState(false);
const [showError, setShowError] = useState(false);

useEffect(() => {
setShowLoader(true);
(async () => {
try {
const response = await getCartAPICall();
const cartItems = response.data.cartItems;
dispatch({ type: "INITIALIZE_CART", payload: { cartItems } });
} catch (error) {
setShowError(error);
} finally {
setShowLoader(false);
setShowError(false);
}
})();
},[]);

return (
<div>
<h1>Cart</h1>
<div>
{showLoader && (<span><Loader /></span>)}
</div>
<div>{showError && <span>Error Occured...</span>}</div>
<div className="cart-grid">
<div className="cart-total">
{itemsInCart.length > 0 ? <CartTotal cart={itemsInCart} /> : ""}
</div>
<div className="container cart-content">
{itemsInCart.length > 0 ? (
itemsInCart.map((item) => (
<div key={item._id}>
<CartCard item={item} />
</div>
))
) : (
<CartEmpty />
)}
</div>
</div>
<ToastContainer />
</div>
);
};
43 changes: 43 additions & 0 deletions src/components/cart/CartCard.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useUserActions } from "../../utilities";

export const CartCard = ({ item }) => {
const { removeFromCartCB, incQtyCB, decQtyCB } = useUserActions();

return (
<div className="card ">
<div className="thumbnail ">
<img
className="card-img"
src={item?.product?.imageURL}
alt="product"
/>
</div>
<div>
<h3>{item?.product?.name}</h3>
<h3>₹{item?.product?.price}</h3>
<button
className={
item?.qty > 1 ? "btn btn-outline" : "btn btn-outline btn-disabled"
}
onClick={() => decQtyCB(item)}
disabled={item?.qty <= 1 ? true : false}
>
-
</button>
<span>{item?.qty}</span>
<button className="btn btn-outline" onClick={() => incQtyCB(item)}>
+
</button>
<span>Sub-Total: ₹{item?.qty * item?.product?.price}</span>
<div>
<button
className="btn btn-filled"
onClick={() => removeFromCartCB(item)}
>
Remove From Cart
</button>
</div>
</div>
</div>
);
};
14 changes: 14 additions & 0 deletions src/components/cart/CartEmpty.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { NavLink } from "react-router-dom";

export const CartEmpty = () => {
return (
<div className="centered-div">
<div className="card card-shadow">
<h3> Your cart is Empty. </h3>
<NavLink to="/" className="link link-empty">
Continue Shopping!
</NavLink>
</div>
</div>
);
};
91 changes: 91 additions & 0 deletions src/components/cart/CartTotal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { useEffect, useState } from "react";
import axios from "axios";
import { useData } from "../../hooks/useData";
import { useNavigate } from "react-router-dom";

const calcTotal = ({ cart }) => {
const {setTotal} = useData();
let totalAmt = [];
totalAmt = cart.map((item) => item?.qty * item?.product?.price);
totalAmt = totalAmt.reduce((acc, val) => acc + val, 0);
setTotal(totalAmt);
return totalAmt;
};

export const CartTotal = (cart) => {
const navigate = useNavigate();
const {total} = useData();

const loadScript = (src) => {
return new Promise((resolve) => {
const script = document.createElement('script');
script.src = src;
script.onload = () => {
resolve(true);
};
script.onerror = () => {
resolve(false);
};
document.body.appendChild(script);
});
};

useEffect(() => {
loadScript('https://checkout.razorpay.com/v1/checkout.js');
});

function payRazorpay() {
console.log("pay!")
displayRazorpay();
}

async function displayRazorpay() {
const { data } = await axios.post(`https://FitKartAPI.pranjalmahajan.repl.co/orders/new`, {
total
});

const options = {
key: 'rzp_test_tYEQjq3P5lM1Rl',
currency: 'INR',
amount: total,
name: 'Fitkart',
description: 'Fitkartt',
order_id: data.id,
handler: function (response) {
console.log(response.razorpay_payment_id);
console.log(response.razorpay_order_id);
},
prefill: {
email: "test@gmail.com",
contact: ''
}
};

const paymentObject = new window.Razorpay(options);
paymentObject.open();

if (data.success === true) {
navigate('/orders');
// const { cart } = await axios.post(`${MAIN_URL}/payment/delete`);
// setItemsInCart(cart);
}
}

return cart.length === 0 ? (
<div className="card">
<div>Cart Total: ₹{total}</div>
<button className="btn btn-filled btn-checkout">Checkout</button>
</div>
) : (
<div className="card">
<div>Cart Total: ₹{calcTotal(cart)}</div>
<button className="btn btn-filled btn-checkout" onClick={() => {
console.log("checkout clicked")
console.log({total})
payRazorpay()
console.log("checkout clicked 1")
}}>
Checkout</button>
</div>
);
};
28 changes: 28 additions & 0 deletions src/components/filters/FilterBy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useData } from "../../hooks/useData";

export const FilterBy = () => {
const { dispatch, includeOutOfStock, fastDeliveryOnly } = useData();
return (
<fieldset>
<legend>Filters</legend>
<label>
<input
type="checkbox"
name="outOfStock"
checked={includeOutOfStock}
onChange={() => dispatch({ type: "TOGGLE_INVENTORY" })}
/>
Include Out Of Stock
</label>
<label>
<input
type="checkbox"
name="fastDelivery"
checked={fastDeliveryOnly}
onChange={() => dispatch({ type: "TOGGLE_DELIVERY" })}
/>
Show Fast Delivery Only
</label>
</fieldset>
);
};
Loading