Giter Site home page Giter Site logo

basir / node-react-ecommerce Goto Github PK

View Code? Open in Web Editor NEW
1.6K 54.0 768.0 420 KB

Build ECommerce Website Like Amazon By React & Node & MongoDB

Home Page: https://node-react-ecommerce-app.herokuapp.com/

HTML 5.75% CSS 9.96% JavaScript 84.28%
redux react node expressjs mongodb mongoose html css javascript axios

node-react-ecommerce's Introduction

React & Node Tutorial - Full ECommerce in 5 Hours [2020]

Welcome to my React and Node tutorial to build a fully-functional e-commerce website in 5 hours. Open your code editor and follow me for the next hours to build an e-commerce website using React and Node.JS.

Demo Website

๐Ÿ‘‰ Demo : https://oldamazona.webacademy.pro

Video Tutorial

๐Ÿ‘‰ Click on this image to watch full 5-hours video of this tutorial

IMAGE ALT TEXT HERE

You Will Learn

  • HTML5 and CSS3: Semantic Elements, CSS Grid, Flexbox
  • React: Components, Props, Events, Hooks, Router, Axios
  • Redux: Store, Reducers, Actions
  • Node & Express: Web API, Body Parser, File Upload, JWT
  • MongoDB: Mongoose, Aggregation
  • Development: ESLint, Babel, Git, Github,
  • Deployment: Heroku
  • Watch React & Node Tutorial

Run Locally

1. Clone repo

$ git clone [email protected]:basir/node-react-ecommerce.git
$ cd node-react-ecommerce

2. Install MongoDB

Download it from here: https://docs.mongodb.com/manual/administration/install-community/

3. Run Backend

$ npm install
$ npm start

4. Run Frontend

# open new terminal
$ cd frontend
$ npm install
$ npm start

5. Create Admin User

6. Login

7. Create Products

Support

Video Tutorials

It gives you an overview of the tutorial to build an eCommerce website like Amazon.

You need to install a code editor and a web browser to start web development. In this part, we will prepare the environment to start coding.

In this part, you create a web template for the eCommerce website. Alt Text

We will create a list of products as static HTML elements.

We will create a hamburger menu that shows and hide the sidebar. Also, we design the details page of the products. Alt Text

This part is about the frontend. We use React library to build the UI elements.

This is the home page of e-commerce. It shows a list of products. Alt Text

When the user clicks on a product there should a page to show details about that product. This lesson is all about making an attractive details page. Alt Text

This part is about Node and Express. They are the popular framework to create a web server using JavaScript language. We will create a MongoDB database and save and retrieve the admin user.

In this lesson, we use React Hooks to fetch data from the server. We use the axios library to do this job in a modern async/await style.

When it comes to handling multiple forms with their data nothing is better than state management. We use Redux in this lesson to handle complex state and keep the app behavior predictable.

In this part, we move the details page state to Redux. First, we create reducers then define actions and connect them to the details component.

Shopping Cart is the heart of any e-commerce website. We focus on creating a user-friendly shopping cart using React and Redux. Alt Text

This lesson is about persisting data on the MongoDB database. We use mongoose package to create models and save and retrieve data from the database.

We need to register the user before redirecting them to the checkout. In this part, we will create forms for getting user info and save them in the database. Alt Text

Admin should be able to define products and update the count in stock whenever they like. This page is about managing ECommerce products. Alt Text

In this part, we implement the checkout wizard including sign in, shipping info, payment method, and place order. Alt Text

Only On Udemy

Following parts are on my udemy course. Get it by 90% discount

Part 18- Order Details Screen

It shows all details about an order includeing shipping, payments and order items. Also it is possible for admin to manage orders like set them as delivered.

Part 19- Connect to PayPal

This parts create PaypalButton component to show paypal payment button on the screen. when users click on it, they will be redirected to paypal website to make the payment. after payment users will be redirected to details page of the order.

Part 20- Manage Order Screen

This is an admin page to manage list of orders. Admin can delete an order or set it as delivered.

Part 21- User Profile Screen

When user click on thier name on the header menu, this page appears. It consists of two sections. First an profile update form and second order history.

Part 22- Filter and Sort Products

In the home page, right after header, there is a filter bar to filter products based on their name and description. also it is possible to sort product based on prices and arrivals.

Part 23- Deploy Website on Heroku

This section explains all steps to publish the ecommerce website on heroku. first you need to create a cloud mongodb and the make an account on heroku.

Part 24- Rate and Review Products

This part shows list of reviews by users for each products. also it provides a form to enter rating and review for every single product. also it update the avg rating of each product by user ratings.

  1. index.html
  2. link fontawesome
  3. Rating.js
  4. create stars based on props.value
  5. show text based on props.text
  6. index.css
  7. style rating, span color gold and last span to gray, link text to blue
  8. HomeScreen.js
  9. use Rating component
  10. ProductScreen.js
  11. use Rating component, wrap it in anchor#reviews
  12. list reviews after product details
  13. create new review form to get rating and reviews
  14. index.css
  15. style reviews
  16. ProductScreen.js
  17. implement submitHandler
  18. productActions.js
  19. create saveProductReview(productId, review)
  20. productConstants.js
  21. create product review constants
  22. productReducers.js
  23. create productReviewSaveReducer
  24. store.js
  25. add productReviewSaveReducer
  26. backend
  27. productRoute.js
  28. router.post('/:id/reviews')
  29. save review in product.reviews
  30. update avg rating

Part 25- Upload Product Images On Local Server

Admin shoud be able to uploads photos from their computer. This section is about uploading images on local server ans aws s3 cloud server.

  1. npm install multer
  2. routes/uploadRoute.js
  3. import express and multer
  4. create disk storage with Date.now().jpg as filename
  5. set upload as multer({ storage })
  6. router.post('/', upload.single('image'))
  7. return req.file.path
  8. server.js
  9. app.use('/api/uploads',uploadRoute)
  10. ProductsScreen.js
  11. create state hook for uploading
  12. create input image file and onChange handler
  13. define handleUploadImage function
  14. prepare file for upload
  15. axios post file as multipart/form-data
  16. set image and set uploading
  17. check result

Part 26- Upload Product Images On AWS S3

This section is about uploading images amazon aws s3 cloud server.

  1. create aws account
  2. open https://s3.console.aws.amazon.com
  3. create public bucket as amazona
  4. create api key and secret
  5. past it into .env as accessKeyId and secretAccessKey
  6. move dotenv to config.js
  7. add accessKeyId and secretAccessKey to config.js
  8. npm install aws-sdk multer-s3
  9. routes/uploadRoute.js
  10. set aws.config.update to config values
  11. create s3 from new aws.S3()
  12. create storageS3 from multerS3 by setting s3, bucket and acl
  13. set uploadS3 as multer({ storage: storageS3 })
  14. router.post('/s3', uploadS3.single('image'))
  15. return req.file.location
  16. ProductsScreen.js
  17. on handleUploadImage set axios.post('api/uploads/s3')
  18. check result on website and s3

Summary

In this tutorial, we have made an eCommerce website like Amazon. Feel free to change this project based on your needs and add it to your portfolio. Also, I will love to hear your comment about this React and Node tutorial. Please share your thoughts here.

node-react-ecommerce's People

Contributors

basir avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-react-ecommerce's Issues

Application can't be started from Heroku

I always see userRoute errors as below. can you please help with me?

2020-06-04T15:41:02.053612+00:00 heroku[web.1]: State changed from crashed to starting
2020-06-04T15:41:04.401044+00:00 heroku[web.1]: Starting process with command node dist/server.js
2020-06-04T15:41:07.747864+00:00 app[web.1]: /app/dist/routes/userRoute.js:23
2020-06-04T15:41:07.747888+00:00 app[web.1]: var _ref = _asyncToGenerator( /#PURE/regeneratorRuntime.mark(function _callee(req, res) {
2020-06-04T15:41:07.747888+00:00 app[web.1]: ^
2020-06-04T15:41:07.747889+00:00 app[web.1]:
2020-06-04T15:41:07.747889+00:00 app[web.1]: ReferenceError: regeneratorRuntime is not defined
2020-06-04T15:41:07.747889+00:00 app[web.1]: at /app/dist/routes/userRoute.js:23:46
2020-06-04T15:41:07.747890+00:00 app[web.1]: at Object. (/app/dist/routes/userRoute.js:75:2)
2020-06-04T15:41:07.747890+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:774:30)
2020-06-04T15:41:07.747891+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
2020-06-04T15:41:07.747891+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:641:32)
2020-06-04T15:41:07.747891+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:556:12)
2020-06-04T15:41:07.747892+00:00 app[web.1]: at Module.require (internal/modules/cjs/loader.js:681:19)
2020-06-04T15:41:07.747892+00:00 app[web.1]: at require (internal/modules/cjs/helpers.js:16:16)
2020-06-04T15:41:07.747892+00:00 app[web.1]: at Object. (/app/dist/server.js:11:41)
2020-06-04T15:41:07.747893+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:774:30)
2020-06-04T15:41:07.747893+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
2020-06-04T15:41:07.747894+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:641:32)
2020-06-04T15:41:07.747894+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:556:12)
2020-06-04T15:41:07.747895+00:00 app[web.1]: at Function.Module.runMain (internal/modules/cjs/loader.js:837:10)
2020-06-04T15:41:07.747895+00:00 app[web.1]: at internal/main/run_main_module.js:17:11
2020-06-04T15:41:07.810785+00:00 heroku[web.1]: Process exited with status 1
2020-06-04T15:41:07.856558+00:00 heroku[web.1]: State changed from starting to crashed

updating the cost of the product not working

8
9

I write as it is as u mention in video, I also copy the code from git repository,but it is not a updating the total cost will we put the product int cart,, multiplu function is not working properly,,,can u please check it

Lecture 11 - Use custom middleware for async actions.

Hello, guys!

I'm getting this error on the Redux DevTools:
error:"Actions must be plain objects. Use custom middleware for async actions."

As you can see, I used thunk in the applyMiddleWare and did import it on the top of the code!

Is this happening with someone?

This is my store.js code:

import {createStore, combineReducers, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk';
import {productListReducer} from './reducers/productReducers';

const initialState = {};
const reducer = combineReducers ({
    productList: productListReducer,
});

const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, initialState, composeEnhancer(applyMiddleware(thunk))); 
export default store; 

And this is my productionActions.js:

import axios from 'axios';

import {
    PRODUCT_LIST_REQUEST,
    PRODUCT_LIST_SUCCESS,
    PRODUCT_LIST_FAIL,
  } from '../constants/productConstants';

const listProducts = () => async(dispatch) => {
    try {
        dispatch(PRODUCT_LIST_REQUEST);
        const {data} = await axios.get("/api/products");
        dispatch({type: PRODUCT_LIST_SUCCESS, payload: data});
    }
    
    catch(error) {
        dispatch({type: PRODUCT_LIST_FAIL, payload: error.message});
    }
} 

export {listProducts}

Headers, authorization

How can i change 'Bearer' to my name?. When i changed it to my name it will be not "invalid token".

i can't install this command npm install @babel/cli @babel/core @babel/node @babel/preset-env --save-dev

PS C:\Users\George Karumathy\Desktop\heeera\amazona> npm install @babel/cli @babel/core @babel/node @babel/preset-env --save-dev
npm WARN deprecated [email protected]: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
npm WARN deprecated [email protected]: fsevents 1 will break on node v14+ and could be using
insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated [email protected]: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated [email protected]: https://github.com/lydell/resolve-url#deprecated
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.7 (node_modules@babel\cli\node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm ERR! Unexpected end of JSON input while parsing near '...BD3cf\n2VY+03BONxT1O7'

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\George Karumathy\AppData\Roaming\npm-cache_logs\2020-06-11T02_20_53_222Z-debug.log

subtotal not adding up

The subtotal does not add up when the value of qty is changed in the cart screen instead it concatenates.
This error can be noticed at 3:07:13 of the project. thank you.

Screenshot (50)

ร— TypeError: Cannot read property 'map' of undefined

HomeScreen
D:/React/Amazona/frontend/src/Screens/HomeScreen.js:25
22 |
23 | return loading ?

Loading...
:
24 | error ?
{error}
:

25 |


    | ^ 26 | {
    27 | products.map(product =>
    28 |

  • View compiled
    โ–ถ 22 stack frames were collapsed.
    (anonymous function)
    D:/React/Amazona/frontend/src/actions/productActions.js:9
    6 | {
    7 | dispatch({type: PRODUCT_LIST_REQUEST});
    8 | const { data } = await axios.get("/api/products");
    9 | dispatch({ type: PRODUCT_LIST_SUCCESS, payroll: data });
    10 | }
    11 |
    12 | catch(error){

image

HomeScreen.js
import React, { useEffect } from 'react';
import { Link} from 'react-router-dom';
// import data from '../data';

import {useSelector, useDispatch} from 'react-redux';
import { listProducts } from '../actions/productActions';

const HomeScreen=(props)=>{

// const [products, setProducts]=useState([]);
const productList = useSelector(state => state.productList);
const { products, loading, error } = productList;
const dispatch = useDispatch();
useEffect(() => {
dispatch(listProducts());

return () => {
  //
};

}, [dispatch])

return loading ? <div>Loading...</div> :
error ? <div>{error}</div> :
<ul className="products">
{
  products.map(product =>
  <li key={product._id}>
    <div className="product">
    <Link to={'/product/' + product._id}><img className="product-image" src={product.image} alt="product" /></Link>
  <div className="product-name" >
      
      <Link to={'/product/' + product._id}>{product.name}</Link>
      </div> 
  <div className="product-brand" >{product.brand}</div> 
  <div className="product-price" >Rs.{product.price}</div>  
  <div className="product-rating" >{product.rating} Star ({product.numReviews})</div>        
</div>
) } } export default HomeScreen;

productActions.js

import { PRODUCT_LIST_REQUEST, PRODUCT_LIST_FAIL, PRODUCT_LIST_SUCCESS } from "../constants/productConstants"
import axios from "axios";

const listProducts = () => async(dispatch) => {
try
{
dispatch({type: PRODUCT_LIST_REQUEST});
const { data } = await axios.get("/api/products");
dispatch({ type: PRODUCT_LIST_SUCCESS, payroll: data });
}

catch(error){
dispatch({type:PRODUCT_LIST_FAIL,payroll:error.message});
}

}

export { listProducts };

productReducers.js
import { PRODUCT_LIST_REQUEST, PRODUCT_LIST_SUCCESS, PRODUCT_LIST_FAIL } from "../constants/productConstants";

function productListReducer(state ={ products: [] }, action){
switch(action.type){
case PRODUCT_LIST_REQUEST:
return{loading:true};
case PRODUCT_LIST_SUCCESS:
return { loading: false, products: action.payload };
case PRODUCT_LIST_FAIL:
return { loading: false, error: action.payload }
default:
return state;

}

}
export{productListReducer};

Issue in signing admin

When I try to give right credentials to the sign-in form. Then it throws error on the server. And when I give wrong credentials then it work correctly saying invalid email password.
Here I am attaching some screenshots
IMG_20200603_133652
Uploading IMG_20200603_133645.jpgโ€ฆ

Not getting info from console

Hello!

This is my first time working with React and Node.

I'm following this tutorial for my first profissional website.
https://youtu.be/Fy9SdZLBTOo?t=4568 (1:16:07)

And I'm not getting the value 1 as a return in the Chorme console in the developer tools.

error_console

I would be super thankfull if you could help me! :D

Thanks for the attention.

Error with the prop

2020-06-20 17_01_51-React App

Hi, i need some help. i'm getting this error while watching the react router part since yesterday and i don't know how to fix it.

Thank you for your videos :3.

Proxy error: could not proxy request /api/products

During Lesson 15, Signin and Resgister screens:

Error on Terminal:
Proxy error: Could not proxy request /api/products from localhost:3000 to http:.

Error on Console:
Failed to load resource, the server responded with a error of :3000/api/products

Error on Web page:
Request failed with status code 404

I tried restarting the terminal and reinstalling the packages but still the same.
my code on github is at: [https://github.com/blasius18/thefrockboutique]

Please help!!

Node backend start error

Hey there again!

I'm getting this error:
error_cmd~

When trying to execute: node backend/server.js.

This is my server.js code:

import express from 'express';
import data from './data';

const app = express();


app.get("/api/products", (req, res) => {
    res.send(data.products);
});

app.listen(5000, () => {
    console.log("server started at at http://localhost:5000");
});

If someone can help and need extra code or information, please tell me and i'll provide it as fast as possible!

Thanks for the attention!!

OnChange is not working in cartScreen.js

While changing the quantity in cart it is not changing. Previous value is being previewed everytime i change the value.
My code:
<select value={item.qty} onChange={(e) => dispatch(addToCart(item.product, e.target.value))}>
{[...Array(item.countInStock).keys()].map(x =>
<option key={x + 1} value={x + 1}>{x + 1}
)}

Application Error

I'm trying to raise the Application to HEROKU

heroku logs --tail:

Cannot find module '/app/dist/server.js'
how can to fix that??

thanks

404 error.

cannot find the /api/products path when trying to use api to get product details

TypeError: Cannot destructure property 'loading' of 'userUpdate' as it is undefined.

21 | dispatch(update({ userId: userInfo._id, email, name, password }))
22 | }
23 | const userUpdate = useSelector(state => state.userUpdate);

24 | const { loading, success, error } = userUpdate;
| ^ 25 |
26 | const myOrderList = useSelector(state => state.myOrderList);
27 | const { loading: loadingOrders, orders, error: errorOrders } = myOrderList;

JS-COOKIE not working

Whenever I try to use JS-cookie to show multiple products in the cart it not being displayed only a single product is displayed every time whenever I click on multiple products to add to cart

Cannot read property 'name' of undefined

Hey there again.

I'm at this time https://youtu.be/Fy9SdZLBTOo?t=4638

And when I compile, the terminal says it was successfully compiled and when I check the react app, I get this error

error_cannot_read

My ProductScreen.js is:

import React from 'react';
import data from '../data';

function ProductScreen(props) {
    console.log(props.match.params.id);
    const product = data.products.find(x => x._id === props.match.params.id);
    return <div>
        <h1> {product.name} </h1>
    </div>
}

export default ProductScreen;

And my data.js is:

export default {
    products: [
        {
            _id: 1,
            name: 'Cozido 1',
            category: 'meals',
            image: '/images/d1.jpg',
            price: 50,
            description: 'asdasdsadasdas',
            rating: 4.0,
            numReviews: 10            
        },

        {
            _id: 2,
            name: 'Cozido 2',
            category: 'meals',
            image: '/images/d1.jpg',
            price: 51,
            description: '1asdasdsadasdas',
            rating: 4.2,
            numReviews: 11         
        },

        {
            _id: 3,
            name: 'Cozido 3',
            category: 'desserts',
            image: '/images/d1.jpg',
            price: 53,
            description: '3asdasdsadasdas',
            rating: 4.235,
            numReviews: 102            
        },
    ]      
}

npm ERR! Failed at the [email protected] start script.

issue

Hi people im doing the ecommerce website amazona with the name project, and i start to have a seriosly issue in the part of connect to MongoDB , when y tried to do the npm start in the project(amazona) the terminal write this issue, im going to anex my code

THIS IS THE CODE server.js
`import express from 'express';
import data from './data';
import dotenv from 'dotenv';
import config from './config';
import mongoose from 'mongoose';
import userRoute from './routes/userRoute';

dotenv.config();

const mongodbUrl = config.MONGODB_URL;
mongoose.connect(mongodbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}).catch(error => console.log(error.reason));

const app = express();

app.user("/api/users", userRoute);
app.get("/api/products/:id", (req, res) => {
const productId = req.params.id;
const product = data.products.find(x=>x._id === productId);
if(product)
res.send(product);
else
res.status(404).send({msg: "Product Not Found."})
});

app.get("/api/products", (req, res) => {
res.send(data.products);
});

app.listen(5000, () => {console.log("Server started at http://localhost:5000") });`

THIS IS THE CODE userRoute.js
`import express from 'express';
import User from '../models/userModel';

const router = express.Router();

router.get("/createadmin", async (req, res) =>{
try{
const user = new User({
name: 'daniel',
email: '[email protected]',
password: '1234',
isAdmin: true
});
const newUser = await user.save();
res.send(newUser);
} catch (error) {
res.send({msg: error.message});
}
});

export default router;
**THIS IS THE CODE userModel.js** import mongoose from 'mongoose';

const userSchema = new mongoose.Schema ({
name:{ type: String, required: true},
email: {type: String, required: true, unique: true, dropDups: true},
password: {type: String, required: true},
isAdmin: { type: Boolean, required: true, default: false}
});

const userModel = mongoose.model("User", userSchema);

export default userModel;`

THIS IS THE CODE config.js
export default { MONGODB_URL: process.env.MONGODB_URL || 'mongodb://localhost/project' }
THIS IS THE CODE package.json
{ "name": "project", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "nodemon --watch backend --exec babel-node backend/server.js" }, "author": "", "license": "ISC", "dependencies": { "dotenv": "^8.2.0", "express": "^4.17.1", "mongodb": "^3.5.9", "mongoose": "^5.9.22" } }
THIS IS THE CODE .env
MONGODB_URL=mongodb://localhost/project

problem with mongodb cannot get connected

ive changed it to mongoAtlas the mongo to connect it via the cloud but it gives me this issue
ps : it didnt work with mongodb because i have it already installed but i dont know how to create another database

E11000 duplicate key error

Trying to add a new user and I'm getting this error even after adding {dropDups: true} to the to the userSchema.
TIME IN PROJECT: 3:21:21, Thank you very much

Screenshot (51)

in Add to Cart button

qty is not working properly,qty not showing the dropdown list to select the quantity.
and the condition written for Add to Cart working not properly that's why this button is not shoeing on the screen

unable to add product in cart

image

CartScreen.js
import React, { useEffect } from 'react';
import { addToCart } from '../actions/cartActions';
import { useDispatch, useSelector } from 'react-redux';

function CartScreen(props) {

const cart = useSelector(state => state.cart);

const { cartItems } = cart;

const productId = props.match.params.id; 
const qty = props.location.search? Number(props.location.search.split("=")[1]) : 1;
const dispatch = useDispatch();
useEffect(() => {
    if (productId) {
      dispatch(addToCart(productId, qty));
    }
  }, []);

  return <div className="cart">
  <div className="cart-list">
    <ul className="cart-list-container">
      <li>
        <h3>
          Shopping cart
        </h3>
        <div>
          Price
        </div>
      </li>
      {
        cartItems.length ===0 ?
        <div>
          Cart is empty
        </div>
        :
        cartItems.map( item =>
          <div>
            <img src={item.image} alt="product" />
            <div className="cart-name">
              <div>
                {item.name}
              </div>
              <div>
                Qty:
                <select>
                  <option value ="1"></option>
                  <option value ="2"></option>
                  <option value ="3"></option>
                  <option value ="4"></option>
                </select>
              </div>
            </div>
            <div>
              {item.price}
            </div>
          </div>
          )
      }
    </ul>
    </div>
    <div className="cart-action">
      <h3>
      Subtotal ( {cartItems.reduce((a, c) => a + c.qty, 0)} items)
    :
     Rs {cartItems.reduce((a, c) => a + c.price * c.qty, 0)}
      </h3>
      <button className="button primary" disabled={cartItems.length === 0}>
    Proceed to Checkout
  </button>
    </div>
  </div>

}
export default CartScreen;

cartReducer.js
import { CART_ADD_ITEM, CART_REMOVE_ITEM, CART_SAVE_SHIPPING, CART_SAVE_PAYMENT } from "../constants/cartConstants";

function cartReducer(state = { cartItems: [] }, action) {
switch (action.type) {
case CART_ADD_ITEM:
const item = action.payload;
const product = state.cartItems.find(x => x.product === item.product);
if (product) {
return {
cartItems:
state.cartItems.map(x => x.product === product.product? item : x)
};
}
return {cartItems: [...state.cartItems], item};
default:
return state
}
}
export { cartReducer}

cartActions.js
import Axios from "axios";

import { CART_ADD_ITEM } from "../constants/cartConstants";

const addToCart = (productId, qty) => async (dispatch) => {
try {
const { data } = await Axios.get("/api/products/" + productId);
dispatch({
type: CART_ADD_ITEM, payload: {
product: data._id,
name: data.name,
image: data.image,
price: data.price,
countInStock: data.countInStock,
qty
}
});

} catch (error) {

}

}
export { addToCart }

i'm download your projeckt to my pc, i cen't run it

'react-scripts' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: react-scripts start
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\SHNEO\AppData\Roaming\npm-cache_logs\2020-06-03T06_03_10_500Z-debug.logPS C:\node-react-ecommerce-master\frontend>

what i need to do???

babel_parse_error

when i try to run the server i get this error

image

SyntaxError: C:\Users\no one\Desktop\root3\myWeb\backend\server.js: Unexpected token (15:21)

13 | const mongodbUrl =config.MONGODB_URL;
14 | mongoose.connect(mongodbUrl, {

15 | useNewUrlParser = true,
| ^
16 | useUnifiedTopology: true,
17 | useCreateIndex: true,
18 | }).catch(error => console.log(error.reason));
at Parser._raise (C:\Users\no one\Desktop\root3\myWeb\node_modules@babel\parser\lib\index.js:746:17)
at Parser.raiseWithData (C:\Users\no one\Desktop\root3\myWeb\node_modules@babel\parser\lib\index.js:739:17)
at Parser.raise (C:\Users\no one\Desktop\root3\myWeb\node_modules@babel\parser\lib\index.js:733:17)
at Parser.unexpected (C:\Users\no one\Desktop\root3\myWeb\node_modules@babel\parser\lib\index.js:8807:16)
at Parser.checkExpressionErrors (C:\Users\no one\Desktop\root3\myWeb\node_modules@babel\parser\lib\index.js:8905:12)
at Parser.parseMaybeAssign (C:\Users\no one\Desktop\root3\myWeb\node_modules@babel\parser\lib\index.js:9469:12)
at Parser.parseExprListItem (C:\Users\no one\Desktop\root3\myWeb\node_modules@babel\parser\lib\index.js:10792:18)
at Parser.parseCallExpressionArguments (C:\Users\no one\Desktop\root3\myWeb\node_modules@babel\parser\lib\index.js:9850:22)
at Parser.parseSubscript (C:\Users\no one\Desktop\root3\myWeb\node_modules@babel\parser\lib\index.js:9750:31)
at Parser.parseSubscripts (C:\Users\no one\Desktop\root3\myWeb\node_modules@babel\parser\lib\index.js:9679:19) {
loc: Position { line: 15, column: 21 },
pos: 407,
code: 'BABEL_PARSE_ERROR'
}
[nodemon] app crashed - waiting for file changes before starting...

Iam not able to run your project in windows 64bit os

backend server started but frontend not working iam getting this error in localhost browser kindly give suggesstion.

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined
at validateString (internal/validators.js:121:11)
at Object.join (path.js:375:7)
at noopServiceWorkerMiddleware (C:\Users\kishan and vijji\Desktop\node-react-ecommerce-master\frontend\node_modules\react-dev-utils\noopServiceWorkerMiddleware.js:14:26)
at Layer.handle [as handle_request] (C:\Users\kishan and vijji\Desktop\node-react-ecommerce-master\frontend\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\kishan and vijji\Desktop\node-react-ecommerce-master\frontend\node_modules\express\lib\router\index.js:317:13)
at C:\Users\kishan and vijji\Desktop\node-react-ecommerce-master\frontend\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\kishan and vijji\Desktop\node-react-ecommerce-master\frontend\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\kishan and vijji\Desktop\node-react-ecommerce-master\frontend\node_modules\express\lib\router\index.js:275:10)
at launchEditorMiddleware (C:\Users\kishan and vijji\Desktop\node-react-ecommerce-master\frontend\node_modules\react-dev-utils\errorOverlayMiddleware.js:20:7)
at Layer.handle [as handle_request] (C:\Users\kishan and vijji\Desktop\node-react-ecommerce-master\frontend\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\kishan and vijji\Desktop\node-react-ecommerce-master\frontend\node_modules\express\lib\router\index.js:317:13)
at C:\Users\kishan and vijji\Desktop\node-react-ecommerce-master\frontend\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\kishan and vijji\Desktop\node-react-ecommerce-master\frontend\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\kishan and vijji\Desktop\node-react-ecommerce-master\frontend\node_modules\express\lib\router\index.js:275:10)
at handleWebpackInternalMiddleware (C:\Users\kishan and vijji\Desktop\node-react-ecommerce-master\frontend\node_modules\react-dev-utils\evalSourceMapMiddleware.js:42:7)
at Layer.handle [as handle_request] (C:\Users\kishan and vijji\Desktop\node-react-ecommerce-master\frontend\node_modules\express\lib\router\layer.js:95:5)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.