CleverProgrammers / react-challenge-amazon-clone

1.03k stars 677 forks source link

unable to generate client secret in console #21

Closed vinender closed 3 years ago

vinender commented 3 years ago

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;`

bibiasha commented 1 year ago

even i am facing the same error