├── public
├── robots.txt
├── favicon.ico
├── logo192.png
├── logo512.png
├── manifest.json
└── index.html
├── src
├── assets
│ └── heroImg.jpg
├── setupTests.js
├── App.test.js
├── reportWebVitals.js
├── index.css
├── index.js
├── components
│ ├── Categories
│ │ └── index.js
│ ├── ProductCard
│ │ └── index.js
│ ├── Hero
│ │ └── index.js
│ ├── Header
│ │ └── index.js
│ ├── FeatureCard
│ │ └── index.js
│ ├── StatCard
│ │ └── index.js
│ └── Footer
│ │ └── index.js
├── App.css
├── modules
│ ├── CategoryProducts
│ │ └── index.js
│ ├── Products
│ │ └── index.js
│ ├── Home
│ │ └── index.js
│ ├── Cart
│ │ └── index.js
│ └── Product
│ │ └── index.js
├── App.js
└── logo.svg
├── tailwind.config.js
├── .gitignore
├── package.json
└── README.md
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Muhammad-Feroz/Ecommerce-App/HEAD/public/favicon.ico
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Muhammad-Feroz/Ecommerce-App/HEAD/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Muhammad-Feroz/Ecommerce-App/HEAD/public/logo512.png
--------------------------------------------------------------------------------
/src/assets/heroImg.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Muhammad-Feroz/Ecommerce-App/HEAD/src/assets/heroImg.jpg
--------------------------------------------------------------------------------
/tailwind.config.js:
--------------------------------------------------------------------------------
1 | /** @type {import('tailwindcss').Config} */
2 | module.exports = {
3 | content: [
4 | "./src/**/*.{js,jsx,ts,tsx}",
5 | ],
6 | theme: {
7 | extend: {},
8 | },
9 | plugins: [],
10 | }
11 |
12 |
--------------------------------------------------------------------------------
/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom';
6 |
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import { render, screen } from '@testing-library/react';
2 | import App from './App';
3 |
4 | test('renders learn react link', () => {
5 | render( );
6 | const linkElement = screen.getByText(/learn react/i);
7 | expect(linkElement).toBeInTheDocument();
8 | });
9 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/src/reportWebVitals.js:
--------------------------------------------------------------------------------
1 | const reportWebVitals = onPerfEntry => {
2 | if (onPerfEntry && onPerfEntry instanceof Function) {
3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
4 | getCLS(onPerfEntry);
5 | getFID(onPerfEntry);
6 | getFCP(onPerfEntry);
7 | getLCP(onPerfEntry);
8 | getTTFB(onPerfEntry);
9 | });
10 | }
11 | };
12 |
13 | export default reportWebVitals;
14 |
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | @tailwind base;
2 | @tailwind components;
3 | @tailwind utilities;
4 |
5 | body {
6 | margin: 0;
7 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
8 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
9 | sans-serif;
10 | -webkit-font-smoothing: antialiased;
11 | -moz-osx-font-smoothing: grayscale;
12 | }
13 |
14 | code {
15 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
16 | monospace;
17 | }
18 |
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom/client';
3 | import './index.css';
4 | import App from './App';
5 | import reportWebVitals from './reportWebVitals';
6 | import { BrowserRouter } from 'react-router-dom';
7 |
8 | const root = ReactDOM.createRoot(document.getElementById('root'));
9 | root.render(
10 |
11 |
12 |
13 |
14 |
15 | );
16 |
17 | // If you want to start measuring performance in your app, pass a function
18 | // to log results (for example: reportWebVitals(console.log))
19 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
20 | reportWebVitals();
21 |
--------------------------------------------------------------------------------
/src/components/Categories/index.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react'
2 | import FeatureCard from '../FeatureCard'
3 |
4 | const Categories = () => {
5 | const [categories, setCategories] = useState([])
6 | useEffect(() => {
7 | const fetchCategories = async () => {
8 | const response = await fetch('https://fakestoreapi.com/products/categories')
9 | const data = await response.json()
10 | console.log(data, 'data')
11 | setCategories(data)
12 | }
13 | fetchCategories()
14 | }, [])
15 |
16 | if (categories.length === 0) return
Loading.....
17 |
18 | return (
19 |
20 | )
21 | }
22 |
23 | export default Categories
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | height: 40vmin;
7 | pointer-events: none;
8 | }
9 |
10 | @media (prefers-reduced-motion: no-preference) {
11 | .App-logo {
12 | animation: App-logo-spin infinite 20s linear;
13 | }
14 | }
15 |
16 | .App-header {
17 | background-color: #282c34;
18 | min-height: 100vh;
19 | display: flex;
20 | flex-direction: column;
21 | align-items: center;
22 | justify-content: center;
23 | font-size: calc(10px + 2vmin);
24 | color: white;
25 | }
26 |
27 | .App-link {
28 | color: #61dafb;
29 | }
30 |
31 | @keyframes App-logo-spin {
32 | from {
33 | transform: rotate(0deg);
34 | }
35 | to {
36 | transform: rotate(360deg);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/modules/CategoryProducts/index.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react'
2 | import { useParams } from 'react-router-dom'
3 | import ProductCard from '../../components/ProductCard'
4 |
5 | const CategoryProducts = () => {
6 | const { name } = useParams()
7 | const [products, setProducts] = useState([])
8 | useEffect(() => {
9 | const fetchProducts = async () => {
10 | const response = await fetch(`https://fakestoreapi.com/products/category/${name}`)
11 | const data = await response.json()
12 | console.log(data)
13 | setProducts(data)
14 | }
15 | fetchProducts()
16 | }, [])
17 |
18 | if (products.length === 0) return Loading.....
19 |
20 | return (
21 |
22 | )
23 | }
24 |
25 | export default CategoryProducts
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import './App.css';
3 | import Footer from './components/Footer';
4 | import Header from './components/Header';
5 | import Home from './modules/Home';
6 | import { Routes, Route } from 'react-router-dom';
7 | import Product from './modules/Product';
8 | import Products from './modules/Products';
9 | import CategoryProducts from './modules/CategoryProducts';
10 | import Cart from './modules/Cart';
11 |
12 | function App() {
13 | return (
14 |
15 |
16 |
17 | } />
18 | } />
19 | } />
20 | } />
21 | } />
22 | 404
} />
23 |
24 |
25 |
26 | );
27 | }
28 |
29 | export default App;
30 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ecommerce",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@testing-library/jest-dom": "^5.16.5",
7 | "@testing-library/react": "^13.4.0",
8 | "@testing-library/user-event": "^13.5.0",
9 | "react": "^18.2.0",
10 | "react-dom": "^18.2.0",
11 | "react-router-dom": "^6.10.0",
12 | "react-scripts": "5.0.1",
13 | "web-vitals": "^2.1.4"
14 | },
15 | "scripts": {
16 | "start": "react-scripts start",
17 | "build": "react-scripts build",
18 | "test": "react-scripts test",
19 | "eject": "react-scripts eject"
20 | },
21 | "eslintConfig": {
22 | "extends": [
23 | "react-app",
24 | "react-app/jest"
25 | ]
26 | },
27 | "browserslist": {
28 | "production": [
29 | ">0.2%",
30 | "not dead",
31 | "not op_mini all"
32 | ],
33 | "development": [
34 | "last 1 chrome version",
35 | "last 1 firefox version",
36 | "last 1 safari version"
37 | ]
38 | },
39 | "devDependencies": {
40 | "tailwindcss": "^3.3.1"
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/modules/Products/index.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react'
2 | import Categories from '../../components/Categories'
3 | import ProductCard from '../../components/ProductCard'
4 |
5 | const Products = () => {
6 | const [products, setProducts] = useState([])
7 | useEffect(() => {
8 | const fetchProducts = async () => {
9 | const response = await fetch('https://fakestoreapi.com/products')
10 | const data = await response.json()
11 | console.log(data)
12 | setProducts(data)
13 | }
14 | fetchProducts()
15 | }, [])
16 |
17 | return (
18 |
19 |
20 |
21 |
PRODUCTS
22 | ALL PRODUCTS
23 |
24 | {
25 | products.length > 0 ?
26 |
27 | :
28 | Loading.....
29 | }
30 |
31 | )
32 | }
33 |
34 | export default Products
--------------------------------------------------------------------------------
/src/modules/Home/index.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react'
2 | import Categories from '../../components/Categories'
3 | import FeatureCard from '../../components/FeatureCard'
4 | import Hero from '../../components/Hero'
5 | import ProductCard from '../../components/ProductCard'
6 | import Products from '../../components/ProductCard'
7 | import Stats from '../../components/StatCard'
8 |
9 | const Home = () => {
10 | const [products, setProducts] = useState([])
11 | useEffect(() => {
12 | const fetchProducts = async () => {
13 | const response = await fetch('https://fakestoreapi.com/products?limit=12')
14 | const data = await response.json()
15 | console.log(data)
16 | setProducts(data)
17 | }
18 | fetchProducts()
19 | }, [])
20 |
21 | return (
22 | <>
23 |
24 |
25 |
26 |
PRODUCTS
27 | MOST POPULAR PRODUCTS
28 |
29 | {
30 | products.length > 0 ?
31 |
32 | :
33 | Loading.....
34 | }
35 |
36 |
37 | >
38 | )
39 | }
40 |
41 | export default Home
--------------------------------------------------------------------------------
/src/components/ProductCard/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Link } from 'react-router-dom';
3 |
4 | const ProductCard = ({ products = [] }) => {
5 | return (
6 |
7 |
8 |
9 | {
10 | products.map((product) => {
11 | console.log(product, 'product')
12 | const { id, title, price, description, category, image } = product;
13 | return (
14 |
15 |
16 |
17 |
18 |
19 |
{category}
20 |
{title}
21 |
${price}
22 |
23 |
24 | )
25 | })
26 | }
27 |
28 |
29 |
30 | )
31 | }
32 |
33 | export default ProductCard
--------------------------------------------------------------------------------
/src/components/Hero/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import heroImg from '../../assets/heroImg.jpg'
3 |
4 | const Hero = () => {
5 | return (
6 |
7 |
8 |
9 |
Get the product now before
10 | they get sold
11 |
12 |
Copper mug try-hard pitchfork pour-over freegan heirloom neutra air plant cold-pressed tacos poke beard tote bag. Heirloom echo park mlkshk tote bag selvage hot chicken authentic tumeric truffaut hexagon try-hard chambray.
13 |
14 | Show All Products
15 | Contact Us
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | )
24 | }
25 |
26 | export default Hero
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 | You need to enable JavaScript to run this app.
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/src/components/Header/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Link } from 'react-router-dom'
3 |
4 | const navigations = [
5 | {
6 | name: 'Home',
7 | path: '/'
8 | },
9 | {
10 | name: 'Products',
11 | path: '/products'
12 | },
13 | {
14 | name: 'About',
15 | path: '/about'
16 | },
17 | {
18 | name: 'Contact',
19 | path: '/contact'
20 | }
21 | ]
22 |
23 | const Header = () => {
24 | return (
25 |
26 |
27 |
28 |
29 |
30 |
31 |
Ecommerce
32 |
33 |
34 | {
35 | navigations.map((navigation) => {
36 | return (
37 | {navigation.name}
38 | )
39 | })
40 | }
41 |
42 |
Go to Cart
43 |
44 |
45 |
46 |
47 |
48 |
49 | )
50 | }
51 |
52 | export default Header
--------------------------------------------------------------------------------
/src/components/FeatureCard/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Link } from 'react-router-dom'
3 |
4 | const FeatureCard = ({cards = [1, 2, 3]}) => {
5 | return (
6 |
7 |
8 |
9 |
CATEGORIES
10 | Our Popular Categories
11 |
12 |
13 | {
14 | cards?.map((card) => {
15 | return (
16 |
17 |
18 |
19 |
24 |
{card || 'Example card'}
25 |
26 |
27 |
Blue bottle crucifix vinyl post-ironic four dollar toast vegan taxidermy. Gastropub indxgo juice poutine.
28 |
Learn More
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 | )
37 | })
38 | }
39 |
40 |
41 |
42 | )
43 | }
44 |
45 | export default FeatureCard
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Getting Started with Create React App
2 |
3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4 |
5 | ## Available Scripts
6 |
7 | In the project directory, you can run:
8 |
9 | ### `npm start`
10 |
11 | Runs the app in the development mode.\
12 | Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
13 |
14 | The page will reload when you make changes.\
15 | You may also see any lint errors in the console.
16 |
17 | ### `npm test`
18 |
19 | Launches the test runner in the interactive watch mode.\
20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21 |
22 | ### `npm run build`
23 |
24 | Builds the app for production to the `build` folder.\
25 | It correctly bundles React in production mode and optimizes the build for the best performance.
26 |
27 | The build is minified and the filenames include the hashes.\
28 | Your app is ready to be deployed!
29 |
30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31 |
32 | ### `npm run eject`
33 |
34 | **Note: this is a one-way operation. Once you `eject`, you can't go back!**
35 |
36 | If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37 |
38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
39 |
40 | You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
41 |
42 | ## Learn More
43 |
44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45 |
46 | To learn React, check out the [React documentation](https://reactjs.org/).
47 |
48 | ### Code Splitting
49 |
50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
51 |
52 | ### Analyzing the Bundle Size
53 |
54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
55 |
56 | ### Making a Progressive Web App
57 |
58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
59 |
60 | ### Advanced Configuration
61 |
62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
63 |
64 | ### Deployment
65 |
66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
67 |
68 | ### `npm run build` fails to minify
69 |
70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
71 |
--------------------------------------------------------------------------------
/src/components/StatCard/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 |
3 | const Stats = () => {
4 | return (
5 |
6 |
7 |
8 |
Master Cleanse Reliac Heirloom
9 |
Whatever cardigan tote bag tumblr hexagon brooklyn asymmetrical gentrify, subway tile poke farm-to-table. Franzen you probably haven't heard of them man bun deep jianbing selfies heirloom prism food truck ugh squid celiac humblebrag.
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
2.7K
19 |
Downloads
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
1.3K
30 |
Users
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
74
40 |
Files
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
46
49 |
Places
50 |
51 |
52 |
53 |
54 |
55 | )
56 | }
57 |
58 | export default Stats
--------------------------------------------------------------------------------
/src/components/Footer/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 |
3 | const Footer = () => {
4 | return (
5 |
119 | )
120 | }
121 |
122 | export default Footer
--------------------------------------------------------------------------------
/src/modules/Cart/index.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react'
2 | import { Link, useNavigate } from 'react-router-dom'
3 |
4 | const Cart = () => {
5 | const navigate = useNavigate()
6 | const [total, setTotal] = useState(0)
7 | const carts = JSON.parse(localStorage.getItem('cart')) || []
8 |
9 | useEffect(() => {
10 | const total = carts.reduce((acc, item) => {
11 | return acc + (item.price * item.quantity)
12 | }, 0)
13 | setTotal(total)
14 | }, [carts])
15 |
16 | const handleInc = (id) => {
17 | const updatedCart = carts.map(item => {
18 | if(item.id === id) {
19 | return {
20 | ...item,
21 | quantity: item.quantity + 1
22 | }
23 | }
24 | return item
25 | })
26 | localStorage.setItem('cart', JSON.stringify(updatedCart))
27 | navigate('/cart')
28 | }
29 |
30 | const handleDec = (id) => {
31 | const updatedCart = carts.map(item => {
32 | if(item.id === id) {
33 | return {
34 | ...item,
35 | quantity: item.quantity - 1
36 | }
37 | }
38 | return item
39 | })
40 | localStorage.setItem('cart', JSON.stringify(updatedCart))
41 | navigate('/cart')
42 | }
43 |
44 | const removeProduct = (id) => {
45 | const updatedCart = carts.filter(item => item.id !== id)
46 | localStorage.setItem('cart', JSON.stringify(updatedCart))
47 | navigate('/cart')
48 | }
49 |
50 | if(carts.length === 0) {
51 | return Cart is Empty
52 | }
53 |
54 | return (
55 |
56 |
57 |
58 |
59 |
Shopping Cart
60 | {carts?.length} Items
61 |
62 |
63 |
Product Details
64 | Quantity
65 | Price
66 | Total
67 |
68 | {
69 | carts?.map(cart => {
70 | return (
71 |
72 |
73 |
74 |
75 |
76 |
77 |
{cart?.title}
78 |
{cart?.category}
79 |
removeProduct(cart?.id)}>Remove
80 |
81 |
82 |
83 |
handleDec(cart?.id)}>
84 |
85 |
86 |
87 |
88 |
handleInc(cart?.id)} viewBox="0 0 448 512">
89 |
90 |
91 |
92 |
${cart?.price}
93 |
${cart?.price * cart?.quantity}
94 |
95 | )
96 | })
97 | }
98 |
99 |
100 |
101 |
102 | Continue Shopping
103 |
104 |
105 |
106 |
107 |
Order Summary
108 |
109 | Items {carts?.length}
110 | {total?.toFixed(2)}$
111 |
112 |
113 | Shipping
114 |
115 | Standard shipping - $10.00
116 |
117 |
118 |
119 | Promo Code
120 |
121 |
122 |
Apply
123 |
124 |
125 | Total cost
126 | ${(total + 10).toFixed(2)}
127 |
128 |
Checkout
129 |
130 |
131 |
132 |
133 |
134 | )
135 | }
136 |
137 | export default Cart
--------------------------------------------------------------------------------
/src/modules/Product/index.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react'
2 | import { useParams, useNavigate } from 'react-router-dom'
3 |
4 | const Product = () => {
5 | const { id } = useParams();
6 | const navigate = useNavigate()
7 | const [product, setProduct] = useState({})
8 | console.log(id, 'id', product)
9 |
10 | useEffect(() => {
11 | const fetchProduct = async () => {
12 | const response = await fetch(`https://fakestoreapi.com/products/${id}`)
13 | const data = await response.json()
14 | console.log(data)
15 | setProduct(data)
16 | }
17 | fetchProduct()
18 | }, [])
19 |
20 | const handleCart = (product, redirect) => {
21 | console.log(product)
22 | const cart = JSON.parse(localStorage.getItem('cart')) || [];
23 | const isProductExist = cart.find(item => item.id === product.id)
24 | if(isProductExist) {
25 | const updatedCart = cart.map(item => {
26 | if(item.id === product.id) {
27 | return {
28 | ...item,
29 | quantity: item.quantity + 1
30 | }
31 | }
32 | return item
33 | })
34 | localStorage.setItem('cart', JSON.stringify(updatedCart))
35 | } else {
36 | localStorage.setItem('cart', JSON.stringify([...cart, {...product, quantity: 1}]))
37 | }
38 | alert('Product added to cart')
39 | if(redirect) {
40 | navigate('/cart')
41 | }
42 | }
43 |
44 | if(!Object.keys(product).length > 0) return Loading.....
45 |
46 | return (
47 |
48 |
49 |
50 |
51 |
52 |
{product?.category}
53 |
{product?.title}
54 |
91 |
{product?.description}
92 |
93 |
94 | Color
95 |
96 |
97 |
98 |
99 |
100 |
Size
101 |
102 |
103 | SM
104 | M
105 | L
106 | XL
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
${product?.price}
118 |
119 | handleCart(product, true)}>Buy it now
120 | handleCart(product)}>Add to cart
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 | )
133 | }
134 |
135 | export default Product
--------------------------------------------------------------------------------