Hi Everyone I am a newbie in React. I am building my react app with typescript and would like to add Stripe to do the online payment. But I cannot find the typescript tutorial on stripe, so I try to use javascript to write the stripe part. But when I trigger the stripe. The errors below appear:
Referring to other solutions on stackOverFlow, i have used different import methods like
import stripe from './stripe';
import * as stripe from './stripe';
but none of them can solve my problem.
What's wrong with my code?
Here are the codes:
For Stripe file:
import React from 'react'
import { Element } from "#stripe/react-stripe-js"
import { loadStripe } from '#stripe/stripe-js'
import "./Stripe.css"
const PaymentForm = require ('./PaymentForm.js')
const PUBLIC_KEY = "pk_test_XXXXXXX"
const stripeTestPromise = loadStripe(PUBLIC_KEY)
export default function Stripe() {
return (
<Element stripe={stripeTestPromise}>
<PaymentForm />
</Element>
)
}
For paymentFrom file:
import React, { useState } from 'react'
import { CardElement, useElements, useStripe } from "#stripe/react-stripe-js"
import * as axios from 'axios'
import "./Stripe.css"
const CARD_OPTIONS = {
iconStyle: "solid",
style: {
base: {
iconColor: "#c4f0ff",
color:"fff",
fontWeight: 500,
fontSize: "16px",
fontSmoothing:"antialiased",
},
invaild: {
iconColor: "#ffc7ee",
color: "ffc7ee"
}
}
}
export default function PaymentForm() {
const [success, setSuccess] = useState(false)
const stripe = useStripe()
const elements = useElements()
const handleSubmit = async (e) => {
e.preventDefault()
const { error, paymentMethod } = await stripe.createPaymentMethod({
type: "card",
card: elements.getElement(CardElement)
})
if (!error) {
try {
const { id } = paymentMethod
const response = await axios.post('http://localhost:8080/checkout', {
amount: 500,
id
})
if (response.data.success) {
console.log('Successful payment')
setSuccess(true)
}
} catch (error) {
console.log('Error', error)
}
} else {
console.log(error.message)
}
}
return (
<div>
{!success ?
<form onSubmit={handleSubmit}>
<fieldset className="FormGroup">
<div className="FormRow">
<CardElement options={CARD_OPTIONS} />
</div>
</fieldset>
<button>Pay</button>
</form >
:
<div>
<h2>You just bought a sweet saptula</h2>
</div>
}
</div>
)
}
I'd like to put a comment but I don't have the reputation to do it, so I'll submit an answer:
If you're trying to insert the elements provider following the documentation
the provider needs to be inserted this way:
import {Elements} from '#stripe/react-stripe-js';
you are importing this like
import {Element} from '#stripe/react-stripe-js';
it's possible that the element you're importing it's an interface or another object and not the provider you want
Related
I am working with Reactjs and Nextjs and i am working on dynamic routes,In other words i have list of blogs and now i want to display blog details for this i created folder name "blogs" and put file name "[slug.js"] inside this but unable to redirect to that url, Here is my current code in Allblog.tsx
<Link href={`/blog/${todoList.id}`}>Edit</Link>
And here is my code inside "blog/[slug.js]"
import Axios from "axios";
import {useRouter} from "next/router";
import { Editor } from '#tinymce/tinymce-react';
//import LatestBlogs from "../../components/LatestBlogs/LatestBlogs";
import Link from 'next/link'
import { useEffect, useState } from 'react'
import Sidebar from '../../components/Sidebar'
const slug = ({ posts }) => {
return(
<div>
<h2> Hello World </h2>
</div>
);
};
export default slug;
export const getStaticProps = async ({ params }) => {
const { data } = await Axios.get(`https://xxxxxxxxxxxxxx/api/getblogbyuserid/${params.slug}`);
const post = data;
return {
props: {
post,
},
};
};
export const getStaticPaths = async () => {
const { data } = await Axios.get("http://xxxxxxxxxxxxxxxxx/api/blogs");
const posts = data.slice(0, 10);
const paths = posts.map((post) => ({ params: { slug: post.id.toString() } }));
return {
paths,
fallback: true,
};
};
file name should be blog/[slug].js
I'm in the process of building a merch e-commerce website for a client utilizing the commerce.js API however I've run into a problem. When passing the "cart" object as a prop to the checkout file it returns as an empty object which breaks the website. The web application passes the "cart" object as a prop in other parts of the code and works just fine. Is there something I'm doing wrong?
Code for reference:
import React, { useState, useEffect } from 'react';
import {Paper, Stepper, Step, StepLabel, Typography, CircularProgress, Divider, Button} from '#material-ui/core';
import { commerce } from '../../../lib/commerce';
import Addressform from '../Addressform';
import Paymentform from '../Paymentform';
const steps =['Shipping Address', 'Payment details'];
const Checkout = ({ cart }) => {
const [activeStep, setActiveStep] = useState(0);
const [checkoutToken, setCheckoutToken] = useState(null);
useEffect (() => {
const generateToken = async () => {
console.log(cart.id);
// returns as undefined
try {
const token = await commerce.checkout.generateToken(cart.id, { type: 'cart' });
console.log(token);
setCheckoutToken(token);
console.log("Success!")
} catch (error) {
console.log(error); //Returns 404 Error Obv
console.log("Didnt work")
}
}
generateToken();
}, []);
const Confirmation = () => (
<>
Confirmation
</>
);
const Form = () => activeStep === 0
? <Addressform />
: < Paymentform />
return(
<>
...
</>
);
};
export default Checkout;
Error:
Compiled with problems:X
ERROR in ./src/App.js 8:0-63
Module not found: Error: Can't resolve '.src/components/NewsCards/NewsCards.js' in '/Users/admin/Desktop/ALAN_AI_NEWS APP/myaiproject/src'
ERROR
src/App.js
Line 7:45: 'useState' is not defined no-undef
Search for the keywords to learn more about each error.
Code:
import React, { useEffect } from 'react';
import alanBtn from '#alan-ai/alan-sdk-web';
import NewsCards from '.src/components/NewsCards/NewsCards.js';
const alanKey = '0f881486602df260f78c6dd18ef0cc6e2e956eca572e1d8b807a3e2338fdd0dc/stage';
const App = () => {
const [newsArticles, setNewsArticles] = useState ([]);
useEffect(() => {
alanBtn({
key: alanKey,
onCommand: ({ command, articles}) => {
if(command === 'newHeadlines') {
setNewsArticles(articles);
// Call the client code that will react to the received command
}
}
})
}, [])
return (
<div>
<h1>Alan AI News Application</h1>
<NewsCards articles={newsArticles} />
</div>
);
}
export default App;
Attached code above, pelase help solve this error
Please import useState hook as well
import React, { useEffect, useState } from 'react';
import alanBtn from '#alan-ai/alan-sdk-web';
const alanKey = '0f881486602df260f78c6dd18ef0cc6e2e956eca572e1d8b807a3e2338fdd0dc/stage';
function NewsCards(props) {
return (
<div>
// your component content
</div>
)
}
export const App = (props) => {
const [newsArticles, setNewsArticles] = useState([]);
useEffect(() => {
alanBtn({
key: alanKey,
onCommand: ({ command, articles}) => {
if(command === 'newHeadlines') {
setNewsArticles(articles);
// Call the client code that will react to the received command
}
}
})
}, [])
return (
<div className='App'>
<h1>Hello React.</h1>
<NewsCards articles={newsArticles} />
</div>
);
}
I'm using react and firebase and trying to implement signing in with google, but the viewport becomes white probably because the function is not being exported from utils file. Because when I delete it from login.js, the components are displayed
This is my code in utils.js
import firebase from 'firebase/app'
import 'firebase/firestore'
import 'firebase/auth'
import {firebaseConfig} from './config'
firebase.initializeApp(firebaseConfig)
export const auth = firebase.auth();
export const firestore = firebase.firestore();
const GoogleProvider = new firebase.auth.GoogleAuthProvider();
GoogleProvider.setCustomParameters({ prompt: 'select_account' });
export const signInWithGoogle = () => auth.signInWithPopup(GoogleProvider);
export default signInWithGoogle
And this is my Login.js
import React, { Component } from 'react'
import './Login.scss'
import Buttons from '../Buttons'
import { signInWithGoogle } from '../../firebase/utils'
class Login extends Component {
handleSubmit = async e => {
e.preventDefault();
}
render() {
return (
<div className='login'>
<div className='login_wrapper'>
<h3 className='login_heading'>Login</h3>
<form className='login_form' onSubmit={this.handleSubmit}>
<Buttons onClick={signInWithGoogle}>
<div className='button_name'>
Sign in with Google
</div>
</Buttons>
</form>
</div>
</div>
)
}
}
export default Login
I also tried to write like this
let signInWithGoogle;
export default signInWithGoogle = () => auth.signInWithPopup(GoogleProvider)
But the console says that signInWithGoogle is not exported from utils.js
I believe the problem is caused by your signInWithGoogle method returning a Promise object which is blocking your component.
You can either change
export const signInWithGoogle = () => auth.signInWithPopup(GoogleProvider);
to (this isn't recommended, as it makes error handling harder)
export const signInWithGoogle = () => { auth.signInWithPopup(GoogleProvider) };
or change how you use it in your component:
import React, { Component } from "react";
import "./Login.scss";
import Buttons from "../Buttons";
import { signInWithGoogle } from "../../firebase/utils";
class Login extends Component {
handleSubmit = async (e) => {
e.preventDefault();
};
render() {
const onClickSignInWithGoogle = () => {
signInWithGoogle() // doesn't return the Promise
.catch((err) => { // don't forget error handling
console.error("Sign in failed!", err);
alert("Failed to sign in!");
});
}
return (
<div className="login">
<div className="login_wrapper">
<h3 className="login_heading">Login</h3>
<form className="login_form" onSubmit={this.handleSubmit}>
<Buttons onClick={onClickSignInWithGoogle}>
<div className="button_name">Sign in with Google</div>
</Buttons>
</form>
</div>
</div>
);
}
}
export default Login;
I'm using https://github.com/expo-community/expo-firebase-starter as a starter template to build a react native app using firebase.
I am working with the following file in Home.js and want to save data to firebase but am getting an error. The error.
firebase.database is not a function. (In 'firebase.database(reflection)', 'firebase.database' is undefined)
Here is the code I'm using. When someone writes a reflection, I'm trying to save that reflection text along with the user ID.
import React, {useEffect, useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import { Container, Content, Header, Form, Input, Item, Label } from 'native-base';
import { Button } from "react-native-elements";
import { withFirebaseHOC } from "../config/Firebase";
import * as firebase from 'firebase';
import "firebase/database";
function Home({ navigation, firebase }) {
const [reflection, setReflection] = useState('');
const[member, setMember] = useState('');
useEffect(() => {
try {
firebase.checkUserAuth(user => {
if (user) {
// if the user has previously logged in
setMember(user);
console.log(member);
} else {
// if the user has previously logged out from the app
navigation.navigate("Auth");
}
});
} catch (error) {
console.log(error);
}
}, []);
async function postReflection() {
try {
await console.log(reflection);
await console.log(member.email);
firebase.database(reflection).ref('Posts/').set({
reflection,
}).then((data)=>{
//success callback
console.log('data ' , data)
}).catch((error)=>{
//error callback
console.log('error ' , error)
})
} catch (error) {
console.log(error);
}
}
async function handleSignout() {
try {
await firebase.signOut();
navigation.navigate("Auth");
} catch (error) {
console.log(error);
}
}
return (
<Container style={styles.container}>
<Form>
<Item floatingLabel>
<Label>Reflection</Label>
<Input
autoCapitalize='none'
autoCorrect={false}
onChangeText={text => setReflection(text)}
/>
</Item>
<Button style = {{ marginTop: 10, marginHorizontal:30 }}
title="Share"
rounded
onPress= {postReflection}
>
</Button>
</Form>
<Button
title="Signout"
onPress={handleSignout}
titleStyle={{
color: "#F57C00"
}}
type="clear"
/>
</Container>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
// justifyContent: "center"
}
});
export default withFirebaseHOC(Home);
Your /config/Firebase/firebase.js doesn't have a database property. Have a look at how the Firebase object is being exported.
// inside /config/Firebase/firebase.js
import "firebase/database"; // add this
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const Firebase = {
// add this
database: () => {
return firebase.database()
}
};
export default Firebase;
Have a read of this step. You can't just import the part of the firebase library, you need to actually assign it to a variable and export it to use it.
https://firebase.google.com/docs/web/setup#namespace
Add the following after import * as firebase from 'firebase';
import "firebase/database";
Each Firebase product has separate APIs that must be added, as described in the documentation.