react-challenge-amazon-clone's People
Forkers
smy5152 ross406 iamkarn07 svsarthakjain hlalwani-max shradhanandan gathasite smitptl matt-l-82 harpreet-singh-au7 bishanmukherjee rahulvish31 cheriaa43 sabreena236 andrewh2o sabbirrifat hassanrkbiz zowiezo od3n tusharwdesai artmazi devfrankduah coryrs cforcross sreechu alprooo elisa-nirin-bi ayeshaazam sayuk09 younouse charlesugwu millerjl1980 devsergeraskin driftgeek roshanlakmal manavkhadka0 choichanmi rafimaleque overwatchh sauraww verdilac sayachoru aykutmayali adi712 alaamohd ayeshacamran karthikas05 codewitchh andiraco yudistira19 hasan-rf vipulvivek ogurenko bozziewilliams ademarrohregger talk2dino saoodahmad pavank313131 victoroluwaseun dhiabenfadhel shubhamkumar5051 rahulprogrammer0 angelo1104 burnjet andiboggs393 chelstay dumitrubrinza shahtufail saumya9712 shivankkunwar robertovr dolfussonia odongohcoder jethrowery danieldev28 dhravmadan22 robertovrz arihant1224 nancyepey jk2uman kevin9f juxlarry micheldas dakom0 viteroberto jamalde dndlc8 a-bakr melody121 vigneshswamy colormebadd abdullahalmasum nadinedeleon saiprasad08dhumal igormuntoreanu nurfrznaaa sanjana17r yosvaldy oliverm1316 aswal2000react-challenge-amazon-clone's Issues
Order pages is not Loading
Facing issue with reducer.js and it is necessary to add webpack as one of the solution suggest to use webpack
Failed to compile
./src/reducer.js 10:16
Module parse failed: Unexpected token (10:16)
You may need an appropriate loader to handle this file type.
| // Selector
| export var getBasketTotal = function getBasketTotal(basket) {
return basket?.reduce(function (amount, item) {
| return item.price + amount;
| }, 0);
This error occurred during the build time and cannot be dismissed.
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!
Please add demo or screenshots
Please add demo or screenshots
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')
},
)
}`
link
in header.js the files are not getting linked to oneanother
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
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)
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;
No Alt for Checkout Ad Image
The alt prop for the image on the checkout page which helps screen readers to identify images is empty.
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 };
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;`
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'
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.
onAuthStateChanged error
TypeError: firebase__WEBPACK_IMPORTED_MODULE_8__.auth.onAuthStateChanged is not a function
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}
export const getBasketTotal = (basket) => basket?.reduce((amount, item) => item.price + amount, 0); getting an error price is not summing it just add items price which is recently added in basket
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
Fix the image path
Amazon logo
Orders page is not opening on clicking buy now
CardElement is just appearing once on in the from after refreshing or redirecting to tha payment page it gets disappear
Please help
Must update react router v5 to v6
I get the error : - TypeError: Cannot read property ‘id’ of undefined in Payment.js
StateProvider.js
payment is not happening as post request is giving 404 error
POST http://localhost:3000/payments/create?total=489800 404 (Not Found)
what to do?
User Authentication
Whenever I hit the Add to Basket Button the User authentication resets
Can anyone tell me how to deploy free on firebase because I'm getting an error Your project clone-8f487 must be on the Blaze (pay-as-you-go) plan to complete this command. Required API cloudbuild.googleapis.com can't be enabled until the upgrade is complete. To upgrade, visit the following URL:
Uncaught (in promise) IntegrationError: Invalid value for stripe.confirmCardPayment intent secret: value should be a client_secret string. You specified: true.
Hi guys. Your app doesn't work on a fresh install. This error occurs: "Unhandled Rejection (IntegrationError): Invalid value for stripe.confirmCardPayment intent secret: value should be a client_secret string. You specified: true." Any ideas on how to solve it.
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.
Cannot deploy the project getting error in index.js file
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)
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 ?
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
Buy now button is not redirecting me to orders page.Please help me
post method in functions/index.js returns 404 err
Errors and their solutions and also Updated Amazon Clone according to react-router-dom v6 and new firebase version
I have written down all the errors and their solutions that I faced while working on amazon clone and at its deployment. I have made this project using all latest version of dependencies. So that, any newbie can implement it without facing any issues.
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
Error: Target container is not a DOM element.
Problem to run Code
Not able to run on linux
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.
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!!!
CardElement not showing in ordersPage
code is same . but , cardElement doesn't display on screen in oredersPage.
reducer.js:23 Uncaught TypeError: Cannot read properties of undefined (reading 'type') i'm calulating total price of basket but it shows this error in inspect>> console .shows error in reducer,js >>>> " switch (action.type)"
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.