Giter Site home page Giter Site logo

react-challenge-amazon-clone's Introduction

This project was bootstrapped with Create React App.

Available Scripts

In the project directory, you can run:

npm start

Runs the app in the development mode.
Open http://localhost:3000 to view it in the browser.

The page will reload if you make edits.
You will also see any lint errors in the console.

npm test

Launches the test runner in the interactive watch mode.
See the section about running tests for more information.

npm run build

Builds the app for production to the build folder.
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.
Your app is ready to be deployed!

See the section about deployment for more information.

npm run eject

Note: this is a one-way operation. Once you eject, you can’t go back!

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.

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.

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.

Learn More

You can learn more in the Create React App documentation.

To learn React, check out the React documentation.

Code Splitting

This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting

Analyzing the Bundle Size

This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size

Making a Progressive Web App

This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app

Advanced Configuration

This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration

Deployment

This section has moved here: https://facebook.github.io/create-react-app/docs/deployment

npm run build fails to minify

This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

react-challenge-amazon-clone's People

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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-challenge-amazon-clone's Issues

Payement does not working

Hello,
at 07:11:05 i have this error :
Uncaught (in promise) IntegrationError: Invalid value for stripe.confirmCardPayment intent secret: value should be a client_secret string. You specified: true.

Any solution ?
I followed the instructions of the video, and checked the code many times, i also compare my code with the Github Code, but i don't find the issue.
Is it a Stripe issue ?

ERROR in ./src/Login.js export 'useHistory' (imported as 'useHistory') was not found in 'react-router-dom'

ERROR in ./src/Login.js 15:18-28

export 'useHistory' (imported as 'useHistory') was not found in 'react-router-dom' (possible exports: BrowserRouter, HashRouter, Link, MemoryRouter, NavLink, Navigate, NavigationType, Outlet, Route, Router, Routes, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, createPath, createRoutesFromChildren, createSearchParams, generatePath, matchPath, matchRoutes, parsePath, renderMatches, resolvePath, unstable_HistoryRouter, useHref, useInRouterContext, useLinkClickHandler, useLocation, useMatch, useNavigate, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRoutes, useSearchParams)

ERROR in ./src/Login.js 131:10-20

export 'useHistory' (imported as 'useHistory') was not found in 'react-router-dom' (possible exports: BrowserRouter, HashRouter, Link, MemoryRouter, NavLink, Navigate, NavigationType, Outlet, Route, Router, Routes, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, createPath, createRoutesFromChildren, createSearchParams, generatePath, matchPath, matchRoutes, parsePath, renderMatches, resolvePath, unstable_HistoryRouter, useHref, useInRouterContext, useLinkClickHandler, useLocation, useMatch, useNavigate, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRoutes, useSearchParams)

Stripe problem

Hey Clever Programmer Team, This is Akshit
I started the amazon clone project and now I am having an issue with the stripe

The issue
I am having an issue when I am processing a payment. When I click on Buy Now the button becomes processing and then the page never responses back and then I go to stripe and it says incomplete payment and I am not returning to the orders page as well

Operating System
Windows 8.1 64-bit

Node Version
v14.15.1

NPM Version
7.19.1

I hope you guys will help

Error

C:\Users\akshit gupta\Desktop\Coding\amazon\amazon\functions>firebase emulators:start
i  emulators: Starting emulators: functions, hosting
!  functions: The following emulators are not running, calls to these services from the
 Functions emulator will affect production: auth, firestore, database, pubsub, storage
+  functions: Using node@14 from host.
i  hosting: Serving hosting files from: build
+  hosting: Local server: http://localhost:5000
i  ui: Emulator UI logging to ui-debug.log
i  functions: Watching "C:\Users\akshit gupta\Desktop\Coding\amazon\amazon\functions" f
or Cloud Functions...
i  hosting: 127.0.0.1 - - [10/Jul/2021:07:57:21 +0000] "GET / HTTP/1.1" 200 2213 "-" "M
ozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/9
1.0.4472.124 Safari/537.36"
i  hosting: 127.0.0.1 - - [10/Jul/2021:07:57:22 +0000] "GET /static/css/main.a52c1e72.c
hunk.css HTTP/1.1" 200 4741 "http://localhost:5000/" "Mozilla/5.0 (Windows NT 6.3; Win6
4; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
i  hosting: 127.0.0.1 - - [10/Jul/2021:07:57:22 +0000] "GET /static/js/main.360367af.ch
unk.js HTTP/1.1" 200 10725 "http://localhost:5000/" "Mozilla/5.0 (Windows NT 6.3; Win64
; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
i  hosting: 127.0.0.1 - - [10/Jul/2021:07:57:23 +0000] "GET /static/js/2.fd4af217.chunk
.js HTTP/1.1" 200 1129303 "http://localhost:5000/" "Mozilla/5.0 (Windows NT 6.3; Win64;
 x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
i  hosting: 127.0.0.1 - - [10/Jul/2021:07:57:25 +0000] "GET /favicon.ico HTTP/1.1" 200
3870 "http://localhost:5000/" "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537
.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
i  hosting: 127.0.0.1 - - [10/Jul/2021:07:57:25 +0000] "GET /manifest.json HTTP/1.1" 20
0 492 "http://localhost:5000/" "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/53
7.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
i  hosting: 127.0.0.1 - - [10/Jul/2021:07:57:26 +0000] "GET /logo192.png HTTP/1.1" 200
5347 "http://localhost:5000/" "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537
.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
+  functions[us-central1-api]: http function initialized (http://localhost:5001/fir-bce
cf/us-central1/api).

┌─────────────────────────────────────────────────────────────┐
│ ?  All emulators ready! It is now safe to connect your app. │
│ i  View Emulator UI at http://localhost:4000                │
└─────────────────────────────────────────────────────────────┘

┌───────────┬────────────────┬─────────────────────────────────┐
│ Emulator  │ Host:Port      │ View in Emulator UI             │
├───────────┼────────────────┼─────────────────────────────────┤
│ Functions │ localhost:5001 │ http://localhost:4000/functions │
├───────────┼────────────────┼─────────────────────────────────┤
│ Hosting   │ localhost:5000 │ n/a                             │
└───────────┴────────────────┴─────────────────────────────────┘
  Emulator Hub running at localhost:4400
  Other reserved ports: 4500

Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the
 *-debug.log files.

i  functions: Beginning execution of "us-central1-api"
i  functions: Finished "us-central1-api" in ~1s
i  functions: Beginning execution of "us-central1-api"
>  Payment Request Recieved BOOM!!! for this amount >>>  9899
i  functions: Finished "us-central1-api" in ~1s
i  functions: Beginning execution of "us-central1-api"
>  Payment Request Recieved BOOM!!! for this amount >>>  0
>  (node:4008) UnhandledPromiseRejectionWarning: Error: This value must be greater than
 or equal to 1.
>      at Function.generate (C:\Users\akshit gupta\Desktop\Coding\amazon\amazon\functio
ns\node_modules\stripe\lib\Error.js:40:16)
>      at IncomingMessage.<anonymous> (C:\Users\akshit gupta\Desktop\Coding\amazon\amaz
on\functions\node_modules\stripe\lib\StripeResource.js:203:33)
>      at Object.onceWrapper (events.js:421:28)
>      at IncomingMessage.emit (events.js:327:22)
>      at endReadableNT (_stream_readable.js:1327:12)
>      at processTicksAndRejections (internal/process/task_queues.js:80:21)
>  (Use `node --trace-warnings ...` to show where the warning was created)
>  (node:4008) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This erro
r originated either by throwing inside of an async function without a catch block, or b
y rejecting a promise which was not handled with .catch(). To terminate the node proces
s on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see
 https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
>  (node:4008) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecate
d. In the future, promise rejections that are not handled will terminate the Node.js pr
ocess with a non-zero exit code.
i  functions: Beginning execution of "us-central1-api"
i  functions: Finished "us-central1-api" in ~1s
i  functions: Beginning execution of "us-central1-api"
>  Payment Request Recieved BOOM!!! for this amount >>>  9899
i  functions: Finished "us-central1-api" in ~1s
!  functions: Your function timed out after ~60s. To configure this timeout, see
      https://firebase.google.com/docs/functions/manage-functions#set_timeout_and_memor
y_allocation.
>  C:\Users\akshit gupta\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\f
unctionsEmulatorRuntime.js:648
>              throw new Error("Function timed out.");
>              ^
>
>  Error: Function timed out.
>      at Timeout._onTimeout (C:\Users\akshit gupta\AppData\Roaming\npm\node_modules\fi
rebase-tools\lib\emulator\functionsEmulatorRuntime.js:648:19)
>      at listOnTimeout (internal/timers.js:554:17)
>      at processTimers (internal/timers.js:497:7)

Error on localhost
Screenshot (326)

My payment.js code

import React, { useState, useEffect } from 'react';
import './Payment.css';
import { useStateValue } from "./StateProvider";
import CheckoutProduct from "./CheckoutProduct";
import { Link, useHistory } from "react-router-dom";
import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
import CurrencyFormat from "react-currency-format";
import { getBasketTotal } from "./reducer";
import axios from './axios';
import { db } from "./firebase";

function Payment() {
    const [{ basket, user }, dispatch] = useStateValue();
    const history = useHistory();

    const stripe = useStripe();
    const elements = useElements();

    const [succeeded, setSucceeded] = useState(false);
    const [processing, setProcessing] = useState("");
    const [error, setError] = useState(null);
    const [disabled, setDisabled] = useState(true);
    const [clientSecret, setClientSecret] = useState(true);

    useEffect(() => {
        // generate the special stripe secret which allows us to charge a customer
        const getClientSecret = async () => {
            const response = await axios({
                method: 'post',
                // Stripe expects the total in a currencies subunits
                url: `/payments/create?total=${getBasketTotal(basket) * 100}`
            });
            setClientSecret(response.data.clientSecret)
        }

        getClientSecret();
    }, [basket])

    console.log('THE SECRET IS >>>', clientSecret)
    console.log('👱', user)

    const handleSubmit = async (event) => {
        // do all the fancy stripe stuff...
        event.preventDefault();
        setProcessing(true);

        const payload = await stripe.confirmCardPayment(clientSecret, {
            payment_method: {
                card: elements.getElement(CardElement)
            }
        }).then(({ paymentIntent }) => {
            // paymentIntent = payment confirmation

            db
              .collection('users')
              .doc(user?.uid)
              .collection('orders')
              .doc(paymentIntent.id)
              .set({
                  basket: basket,
                  amount: paymentIntent.amount,
                  created: paymentIntent.created
              })

            setSucceeded(true);
            setError(null)
            setProcessing(false)

            dispatch({
                type: 'EMPTY_BASKET'
            })

            history.replace('/orders')
        })

    }

    const handleChange = event => {
        // Listen for changes in the CardElement
        // and display any errors as the customer types their card details
        setDisabled(event.empty);
        setError(event.error ? event.error.message : "");
    }

    return (
        <div className='payment'>
            <div className='payment__container'>
                <h1>
                    Checkout (
                        <Link to="/checkout">{basket?.length} items</Link>
                        )
                </h1>


                {/* Payment section - delivery address */}
                <div className='payment__section'>
                    <div className='payment__title'>
                        <h3>Delivery Address</h3>
                    </div>
                    <div className='payment__address'>
                        <p>{user?.email}</p>
                        <p>123 React Lane</p>
                        <p>Los Angeles, CA</p>
                    </div>
                </div>

                {/* Payment section - Review Items */}
                <div className='payment__section'>
                    <div className='payment__title'>
                        <h3>Review items and delivery</h3>
                    </div>
                    <div className='payment__items'>
                        {basket.map(item => (
                            <CheckoutProduct
                                id={item.id}
                                title={item.title}
                                image={item.image}
                                price={item.price}
                                rating={item.rating}
                            />
                        ))}
                    </div>
                </div>
            

                {/* Payment section - Payment method */}
                <div className='payment__section'>
                    <div className="payment__title">
                        <h3>Payment Method</h3>
                    </div>
                    <div className="payment__details">
                            {/* Stripe magic will go */}

                            <form onSubmit={handleSubmit}>
                                <CardElement onChange={handleChange}/>

                                <div className='payment__priceContainer'>
                                    <CurrencyFormat
                                        renderText={(value) => (
                                            <h3>Order Total: {value}</h3>
                                        )}
                                        decimalScale={2}
                                        value={getBasketTotal(basket)}
                                        displayType={"text"}
                                        thousandSeparator={true}
                                        prefix={"$"}
                                    />
                                    <button disabled={processing || disabled || succeeded}>
                                        <span>{processing ? <p>Processing</p> : "Buy Now"}</span>
                                    </button>
                                </div>

                                  {/* Errors */}
                                {error && <div>{error}</div>}
                            </form>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Payment;

react-router-dom only works on reload

When I click a cart that triggers a redirect, The URL changes to the appropriate route. But the cart component does not appear. If I reload the page, I get the cart.

Firebase hosting site is being deployed

Hey, idk what's the problem in my code actually my website worked well using npm start amazon clone.. But, when i am deploying it using firebase my site got deployed but i see some firebase hosting interface am i deploying something different? Can please someone help me

Uncaught (in promise) FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore

`import React, { useEffect, useState } from "react";
import CheckoutProduct from "./CheckoutProduct";
import "./Payment.css";
import { useStateValue } from "./StateProvider";
import { Link, useNavigate } from "react-router-dom";
import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js";
import CurrencyFormat from "react-currency-format";
import { getBasketTotal } from "./reducer";
import axios from "./axios";
import { auth } from "./firebase";
import { db } from "./firebase";
import { doc, setDoc } from "firebase/firestore";
import { collection, addDoc } from "firebase/firestore";
import { async } from "@firebase/util";

function Payment() {
const [{ basket, user }, dispatch] = useStateValue();
const history = useNavigate();
const stripe = useStripe();
const elements = useElements();

const [succeeded, setSucceeded] = useState(false);
const [processing, setProcessing] = useState("");
const [error, setError] = useState(null);
const [disabled, setDisabled] = useState(true);
const [clientSecret, setClientSecret] = useState(true);

useEffect(() => {
//generate the special stripe secret which allows us to charge a customer
const getClientSecret = async () => {
const response = await axios({
method: "post",
// Stripe expects the total in a currencies subunits
url: /payments/create?total=${getBasketTotal(basket) * 100},
});
setClientSecret(response.data.clientSecret);
};
getClientSecret();
}, [basket]);

console.log("THE SECRET IS >>>>>", clientSecret);

const handleSubmit = async (event) => {
//do all the fancy stripe stuff
event.preventDefault();
setProcessing(true);

const payload = await stripe
  .confirmCardPayment(clientSecret, {
    payment_method: {
      card: elements.getElement(CardElement),
    },
  })

.then(({ paymentIntent }) => {
// db.collection("users")
// .doc(user?.uid)
// .collection("orders")
// .doc(paymentIntent.id)
// .set({
// basket: basket,
// amount: paymentIntent.amount,
// created: paymentIntent.created,
// });

const docRef = doc(collection(db, "users", user?.uid));
const newRef = doc(collection(docRef, "orders", paymentIntent?.id));
setDoc(newRef, {
basket: basket,
amount: paymentIntent.amount,
created: paymentIntent.created,
});

setSucceeded(true);
setError(null);
setProcessing(false);
//history.replace("/orders");
dispatch({
type: "EMPTY_BASKET",
user: auth,
});
history("/orders", { replace: true });
});
};

const handleChange = (event) => {
//listen for changes in the card element
// and display any error as the customer types their card detail
setDisabled(event.empty);
setError(event.error ? event.error.message : "");
};
return (




Checkout ({basket?.length} Items)


{/* Payment section - delivery address /}
{/
Payment section - Review Items /}
{/
Payment section - Payment Method */}

    <div className="payment__section">
      <div className="payment__title">
        <h3>Delivery Address</h3>
        <div className="payment__address">
          <p>{user?.email}</p>
          <p>123 React Lane</p>
          <p> Los Angeles, CA</p>
        </div>
      </div>
    </div>
    <div className="payment__section">
      <div className="payment__title">
        <h3>Review Items and Delivery</h3>
      </div>
      <div className="payment__items">
        {basket.map((items) => (
          <CheckoutProduct
            id={items.id}
            title={items.title}
            image={items.image}
            price={items.price}
            rating={items.rating}
          />
        ))}
      </div>
    </div>
    <div className="payment__section">
      <div className="payment__title">
        <h3>Payment Method</h3>
      </div>
      <div className="payment__details">
        {/* Here the stripe magic will go */}
        <form onSubmit={handleSubmit} action="">
          <CardElement onChange={handleChange} />
          <div className="payment__priceContainer">
            <CurrencyFormat
              renderText={(value) => (
                <>
                  <h3>Order Total: {value}</h3>
                </>
              )}
              decimalScale={2}
              value={getBasketTotal(basket)}
              displayType={"text"}
              thousandSeparator={true}
              prefix={"$"}
            />
            <button disabled={processing || disabled || succeeded}>
              <span>{processing ? <p>Processing</p> : "Buy now"}</span>
            </button>
          </div>

          {/* Error */}
          {error && <div>{error}</div>}
        </form>
      </div>
    </div>
  </div>
</div>

);
}

export default Payment;
`

I think its due to the firebase v8 to v9 but i tried changing the code to v9 but I cant get grasp of it.... can someone
db.collection("users") .doc(user?.uid) .collection("orders") .doc(paymentIntent.id) .set({ basket: basket, amount: paymentIntent.amount, created: paymentIntent.created, });
convert this code into v9 because of this I am not able to complete the clone plz help

ERROR in ./src/firebase.js - npm start

I was trying to run the project on my local system using npm start in developer mode, as stated in the README.md and encountered this error:

ERROR in ./src/firebase.js 3:0-32
Module not found: Error: Package path . is not exported from package D:\Code\react-challenge-amazon-clone\node_modules\firebase (see exports field in D:\Code\react-challenge-amazon-clone\node_modules\firebase\package.json)
Did you mean './firebase'?
Requests that should resolve in the current directory need to start with './'.
Requests that start with a name are treated as module requests and resolve within module directories (node_modules, D:\Code\react-challenge-amazon-clone\node_modules).
If changing the source code is not an option there is also a resolve options called 'preferRelative' which tries to resolve these kind of requests in the current directory too.

The fix which I could find is changing the import statements of the src/firebase.js file. I have open a pull request with the changes please review and merge.

Firebase Error: Failed to compile: Module not found: Can't resolve 'firebase' in

Received the following error. Have been beating my head against a wall for about a week now. Not sure what I've done wrong. I've tried installing the tools, installing them globally, and installing them with administrator privileges. I started another project from scratch to see if I made any errors in what I was doing. I reinstalled my operating system to make sure that I hadn't screwed up my settings somehow. I even went to the written instructions and just copied and pasted into the file to make sure there weren't any spelling errors. For the life of me I can't figure out why I'm getting this error. Additionally, I'm not getting this error on my desktop computer, only on my laptop. When I open it with my desktop computer, everything compiles and works fine. Any help would be greatly appreciated.

Failed to compile.

./src/firebase.js
Module not found: Can't resolve 'firebase' in 'C:\Users...\src'

import firebase from "firebase";

const firebaseConfig = {

  apiKey: ****
  authDomain: ****
  projectId: ****
  storageBucket: ****
  messagingSenderId: ****
  appId: ****
  measurementId: ****
};

const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebase.auth();

export { db, auth };

Stripe payment

For any Indian thinking, stripe payment is why not succeeding and not showing on the stripe dashboard, don't worry Indian gov. has banned it
"As per Indian regulations, only registered Indian businesses (i.e. sole proprietorships, limited liability partnerships, and companies, but not individuals) can accept international payments. More info here: https://stripe.com/docs/india-exports"
so paymentIntent would be coming out empty, you can check this out by writing console.log(result) in payment.js and pass result instead of {paymentIntent}

currencyFormat in Subtotal.js is not working

In subtotal.js when I code for CurrencyFormat I only get an input field in output and when I go for inspect option in chrome then the code for currency format is not showing instead of that I get a single line code for the input field. Plz help me with this issue asap

Buy Now button not working.

Unhandled Rejection (TypeError): Cannot read property 'id' of undefined

I have completed 7.37.03 on the recent youtube video on amazon-clone (Full E-Comm Store in 8 hrs)

I matched each line of code.
Error being in Payment.js, on the lines 47 & 54

47 : const payload = await stripe.confirmCardPayment(clientSecret, {

54 : db .collection('users') .doc(user?.uid) .collection('orders') .doc(paymentIntent.id) .set({ basket: basket, amount: paymentIntent.amount, created: paymentIntent.created })

This one doesn't fix. Even did the uid correction.
Help much much much appreciated!!!

Need a help with connection to basket

Hello guys! First thank you so much for great tutorial, it's very valuable. I also need a help with connection to basket. Till 2:20:42 everything worked perfectly, on the Home page items adding to basket, but when I'm going to Checkout page it's go to 0 again. Subtotal (0 items) doesn't work as well. Maybe anyone had the same issue? Thank you!

Issue in after processing the card details the stripe details is not shown in the stripe dashboard.

import React, { useState, useEffect } from 'react';
import './Payment.css';
import { useStateValue } from "./StateProvider";
import CheckoutProduct from "./CheckoutProduct";
import { Link } from "react-router-dom";
import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
import CurrencyFormat from "react-currency-format";
import { getBasketTotal } from "./reducer";
import axios from './axios';
import { db } from "./firebase";
import { useNavigate } from 'react-router-dom';

function Payment() {
const [{ basket, user }, dispatch] = useStateValue();
const navigate = useNavigate();

const stripe = useStripe();
const elements = useElements();

const [succeeded, setSucceeded] = useState(false);
const [processing, setProcessing] = useState("");
const [error, setError] = useState(null);
const [disabled, setDisabled] = useState(true);
const [clientSecret, setClientSecret] = useState(true);

useEffect(() => {
    // generate the special stripe secret which allows us to charge a customer
    const getClientSecret = async () => {
        const response = await axios({
            method: 'post',
            // Stripe expects the total in a currencies subunits
            url: `/payments/create?total=${getBasketTotal(basket) * 100}`
        });
        setClientSecret(response.data.clientSecret)
    }

    getClientSecret();
}, [basket])

console.log('THE SECRET IS >>>', clientSecret)
console.log('👱', user)

const handleSubmit = async (event) => {
    // do all the fancy stripe stuff...
    event.preventDefault();
    setProcessing(true);

    const payload = await stripe.confirmCardPayment(clientSecret, {
        payment_method: {
            card: elements.getElement(CardElement)
        }
    }).then(({ paymentIntent }) => {
        // paymentIntent = payment confirmation

        db.collection('users').doc(user?.uid).collection('orders').doc(paymentIntent.id).set({
            basket: basket,
            amount: paymentIntent.amount,
            created: paymentIntent.created
        })

        setSucceeded(true);
        setError(null)
        setProcessing(false)

        dispatch({
            type: 'EMPTY_BASKET'
        })

        navigate('/orders')
    })

}

const handleChange = event => {
    // Listen for changes in the CardElement
    // and display any errors as the customer types their card details
    setDisabled(event.empty);
    setError(event.error ? event.error.message : "");
}

return (
    <div className='payment'>
        <div className='payment__container'>
            <h1>
                Checkout (
                <Link to="/checkout">{basket?.length} items</Link>
                )
            </h1>


            {/* Payment section - delivery address */}
            <div className='payment__section'>
                <div className='payment__title'>
                    <h3>Delivery Address</h3>
                </div>
                <div className='payment__address'>
                    <p>{user?.email}</p>
                    <p>123 React Lane</p>
                    <p>Los Angeles, CA</p>
                </div>
            </div>

            {/* Payment section - Review Items */}
            <div className='payment__section'>
                <div className='payment__title'>
                    <h3>Review items and delivery</h3>
                </div>
                <div className='payment__items'>
                    {basket.map(item => (
                        <CheckoutProduct
                            id={item.id}
                            title={item.title}
                            image={item.image}
                            price={item.price}
                            rating={item.rating}
                        />
                    ))}
                </div>
            </div>


            {/* Payment section - Payment method */}
            <div className='payment__section'>
                <div className="payment__title">
                    <h3>Payment Method</h3>
                </div>
                <div className="payment__details">
                    {/* Stripe magic will go */}

                    <form onSubmit={handleSubmit}>
                        <CardElement onChange={handleChange} />

                        <div className='payment__priceContainer'>
                            <CurrencyFormat
                                renderText={(value) => (
                                    <h3>Order Total: {value}</h3>
                                )}
                                decimalScale={2}
                                value={getBasketTotal(basket)}
                                displayType={"text"}
                                thousandSeparator={true}
                                prefix={"$"}
                            />
                            <button disabled={processing || disabled || succeeded}>
                                <span>{processing ? <p>Processing</p> : "Buy Now"}</span>
                            </button>
                        </div>

                        {/* Errors */}
                        {error && <div>{error}</div>}
                    </form>
                </div>
            </div>
        </div>
    </div>
)

}

export default Payment

I am using this code, and having the issue when i enter the card details, it doesn't proceed after that, it only shows processing. Please anyone help me to resolve this issue!

unable to generate client secret in console

Without any error the setClientSecret() unable to set the clientSecret, returns only initial value as truein console.

Payment.js file

`import React,{useState, useEffect} from 'react';
import './Payment.css';
import {useStateValue} from './StateProvider';
import CheckoutProduct from './CheckoutProduct.js';
import {Link, useHistory} from 'react-router-dom';
import {CardElement, useStripe, useElements} from '@stripe/react-stripe-js';
import CurrencyFormat from 'react-currency-format';
import {getBasketTotal} from './reducer';
import axios from './axios';
import { db } from '..firebase/firebase';

const Payment = () => {
const [{basket, user}, dispatch] = useStateValue();
const history = useHistory();

const stripe = useStripe();
const elements = useElements();

const [error, setError]= useState(null);
const [disabled, setDisabled] = useState(true);

const [succeeded, setSucceeded] = useState(false);
const [processing, setProcessing] = useState('');

const [clientSecret, setClientSecret] = useState(true);


 useEffect(() => {
    // generate the special stripe secret which allows us to charge a customer
    const getClientSecret = async () => {
        const response = await axios({
            method: 'post',
            // Stripe expects the total in a currencies subunits
            url: ` /payments/create?total=${getBasketTotal(basket) * 100}`
        });
        setClientSecret(response.data.clientSecret)
    }

    getClientSecret();
}, [basket])

 // console.log('clientSecret', response.data.clientSecret)

 console.log('the Secret Is >>', clientSecret);



const handleSubmit = async (e) => {
	e.preventDefault();
	setProcessing(true);

	const payload = await stripe.confirmCardPayment(clientSecret, {
		payment_method: {
			card: elements.getElement(CardElement)
		}
	}).then(({ paymentIntent }) => {
		// paymentIntent = payment confirmation
		db
		.collection('users')
		.doc(user?.uid)
		.collection('orders')
		.doc(paymentIntent.id)
		.set({
			basket: basket,
			amount: paymentIntent.amount,
			created: paymentIntent.created 
		})

		setSucceeded(true);
		setError(null)
		setProcessing(false)

		dispatch({
			type: 'EMPTY_BASKET'
		})

		history.replace('/orders')
	})

}

const handleChange = (e) => {
	setDisabled(e.empty);
	setError(e.error ? e.error.message : '');

}

return (
	<div className='payment'>

		<div className='payment__container'>
			<h1>
				Checkout (
				<Link to='/checkout'>{basket?.length} items
				</Link> 
				)
			</h1>
			
			<div className='payment__section'>
				
				<div className='payment__title'>
					<h3>Address</h3>
				</div>

				<div className='payment__address'>
					<p>{user?.email}</p>
					<p>123 react lane</p>
					<p>Los Angeles</p>
				</div> 
		    </div>

			<div className='payment__section'>
				<div className='payment__title'>
					<h3>Review Items and Delivery</h3>
					
				</div>

				<div className='payment__items'>
					{basket.map((item)=> (
					<CheckoutProduct
						
						id={item.id}
						price={item.price}
						rating={item.rating}
						image={item.image}
						title={item.title}
						/>
					))}
				</div>
				
			</div>

			<div className='payment__section'>

				<div className='payment__title'>
					<h3>Payment Method</h3>
				</div>

				<div className='payment__details'>

					<form onSubmit={handleSubmit}>

						<CardElement onChange={handleChange}/>

						<div className='payment__priceContainer'>
							<CurrencyFormat
					        renderText={(value) => (
					        	<h3> Order Total: {value}</h3>
					        )}
					        decimalScale={2}
					        value={getBasketTotal(basket)} 
					        displayType={"text"}
					        thousandSeparator={true}
					        prefix={"₹"}
				           />

				           <button disabled={processing || disabled || succeeded}>
				           	<span>{processing ? <p>Processing....</p> : 'Buy Now'}</span>
				           </button>
						</div>
                         
                         {/* In case there is an error */}
						{error && <div>{error}</div>}

					</form>
					
				</div>
				
			</div>

			

		</div>
	
	</div>
)

}

export default Payment;`

Error: Target container is not a DOM element.

This issue came after I started the firebase emulator and I'm unable to resolve it even after soo many attempts. Also the title of the
app changed from React App to Welcome to Firebase Hosting.

Screenshot (378)

When I click on the buy now button I get a bug Error, the payment gets processed but the error dosen't show the orders page

When I click on the buy now button the payment gets processed, but I get this error: Unhandled Rejection (FirebaseError): Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in document users/62IdRaWYZNXkX4iZYDoXiRlBytf2/orders/pi_1I7crQIA89ysljXolGJcgaLK)

Thank you in advance and it would mean the world to me if someone could help me.

}
55 | }).then(({ paymentIntent }) => {
56 | //paymentIntent = payment confirmation

57 | db
| ^ 58 | .collection('users')
59 | .doc(user?.uid)
60 | .collection('orders'

link

in header.js the files are not getting linked to oneanother

All links on login page Do NOT load page

Will like to start by appreciating your efforts for this superbly designed challenge(kudos).

My issue is that I've followed the challenge up to login/authentication. But the on the image and the successful account creation change th e url to home (ie localhost:3000) but index page ("/" ) neva loads; it just remain on the login page unkes I hit the refresh button.
I've checked stark overflow for possible fix with some suggesting the use of placing the home route first on the switch list and using 'exact' keyword but to no avail.

Thanks - I really need to finish this project as I've enjoyed every bit of it.

Unhandled Rejection (FirebaseError): Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in document users/tDJ1zI9JWwakZdq5CkFh/orders/pi_1ILaCRDbKBqU3OnKnhbGH0Dv)

The error in the Payment.js section where we using no sql db.collection('users') if anyone solve this erorr pls help me

import React, { useState, useEffect } from 'react'
import "./Payment.css";
import { useStateValue } from "./StateProvider";
import CheckoutProduct from "./CheckoutProduct"
import { Link, useHistory } from "react-router-dom"
import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
import CurrencyFormat from 'react-currency-format';
import { getBasketTotal } from "./reducer";
import axios from './axios';
import { db } from "./firebase";

function Payment() {
const [{ basket, user, }, dispatch] = useStateValue();
const history = useHistory();

const stripe = useStripe();
const elements = useElements();

const [succeeded, setSucceeded] = useState(false);
const [processing, setProcessing] = useState("");
const [error, setError] = useState(null);
const [disabled, setDisabled] = useState(true);
const [clientSecret, setClientSecret] = useState(true);

useEffect(() => {
    //generate a special stripe code to allow us to charge customer
    const getClientSecret = async () => {
        const response = await axios({
            method: 'post',
            url: `/payments/create?total=${getBasketTotal(basket) * 100}`
        });
        setClientSecret(response.data.clientSecret)
    }

    getClientSecret();

}, [basket])

console.log('The Secret is', clientSecret)
console.log('hello', user)

const handleSubmit = async (event) => {
    event.preventDefault();
    setProcessing(true);

    // eslint-disable-next-line no-unused-vars
    const payload = await stripe.confirmCardPayment(clientSecret, {
        payment_method: {
            card: elements.getElement(CardElement)
        }
    }).then(({ paymentIntent }) => {

        db
            .collection('users')
            .doc(user?.uid)
            .collection('orders')
            .doc(paymentIntent.id)
            .set({
                basket: basket,
                amount: paymentIntent.amount,
                created: paymentIntent.created
            })

        setSucceeded(true);
        setError(null);
        setProcessing(false);

        dispatch({
            type: 'EMPTY_BASKET'
        })

        history.replace('/orders')
    })
}

const handleChange = event => {
    //Listen for the changes in the card element
    //and display any errors as the customer type their card details
    setDisabled(event.empty);
    setError(event.error ? event.error.message : "");

}

return (
    <div className="payment">
        <div className="payment_container">
            <h1>
                Checkout (<Link to='/checkout'>{basket?.length} items</Link>)
            </h1>
            {/* delivery address */}
            <div className="payment_section">
                <div className="payment_title">
                    <h3>Delivery Address</h3>
                </div>
                <div className="payment_address">
                    <p>{user?.email}</p>
                    <p>Street 4</p>
                    <p>Islambad</p>
                </div>

            </div>

            {/* Review Items */}
            <div className="payment_section">
                <div className="payment_title">
                    <h3>Review Items and Delivery</h3>
                </div>
                <div className="payment_items">
                    {basket.map(item => (
                        < CheckoutProduct
                            id={item.id}
                            title={item.title}
                            image={item.image}
                            price={item.price}
                            rating={item.rating}
                        />
                    ))}
                </div>
            </div>

            {/* Payment Method */}
            <div className="payment_section">
                <div className="payment_title">
                    <h3>Payment Method</h3>
                </div>
                <div className="payment_details">

                    <form onSubmit={handleSubmit}>
                        <CardElement onChange={handleChange} />
                        <div className="payment_priceContainer">
                            <CurrencyFormat
                                renderText={(value) => (
                                    <h3>Order Total: {value}</h3>

                                )}
                                decimalScale={2}
                                value={getBasketTotal(basket)}
                                displayType={"text"}
                                thousandSeparator={true}
                                perfix={"$"}
                            />
                            <button disabled={processing || disabled || succeeded}>
                                <span> {processing ? <p>Processing</p> : "Buy Now"}</span>
                            </button>
                        </div>
                        {error && <div>{error}</div>}
                    </form>
                </div>

            </div>

        </div>

    </div>
)

}

export default Payment

Stripe API error, Indian regulation law causing payment error

Developing an eCommerce with Stripe payment gateway, and facing this error every time.

As mentioned in here I have to provide the customer's name, billing address, description, and shipping address, otherwise, the payment will fail, it's a govt law regulated in India.

This is the error I am getting in Stripe API logs

invalid_request_error - description As per Indian regulations, export transactions require a description. More info here: https://stripe.com/docs/india-exports

How do I fix this?

This is the handleSubmit which cause the data transfer to the backend:

`const handleSubmit = async (event) => {
// do all the fancy stripe stuff...
event.preventDefault();
setProcessing(true);

        const payload = await stripe.confirmCardPayment(clientSecret, {
            payment_method: {
                card: elements.getElement(CardElement),
            }
        }}            
        ).then(({ error, paymentIntent }) => {
            // paymentIntent = payment confirmation

                db
                  .collection('users')
                  .doc(user?.uid)
                  .collection('orders')
                  .doc(paymentIntent.uid)
                  .set({
                      basket: basket,
                      amount: paymentIntent.amount,
                      created: paymentIntent.created,

                  })
    
                setSucceeded(true);
                setError(null)
                setProcessing(false)
    
                dispatch({
                    type: 'EMPTY_BASKET'
                })
        
                history.replace('/orders')
        },
        )
    
    }`

Linking issue at 1:47:00

I'm facing linking issue. I downgrade the package version and there is no error in switch but whenever i click on basket or amazon logo , url changed after clicking but content remains same. Please Help me. It's urgent. Thankyou in Advance.

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.