Ahoy,
Getting an error with Stripe in Gatsby occurs on page load
Uncaught (in promise) TypeError: maybeStripe.apply is not a function
import React, { useEffect, useState } from 'react';
import { loadStripe } from '#stripe/stripe-js';
import { Elements } from '#stripe/react-stripe-js';
import StripeCheckout from './stripeCheckout'
const stripePromise = loadStripe('pk_test_xyz');
function App() {
const [clientSecret, setClientSecret] = useState('');
useEffect(() => {
fetch("/.netlify/functions/createIntent")
.then((res) => res.json())
.then(({ clientSecret }) => setClientSecret(clientSecret));
}, [])
const options = {
clientSecret,
}
return (
<main>
<h1>Payment</h1>
{clientSecret && (
<Elements stripe={stripePromise} options={options}>
<StripeCheckout />
</Elements>
)}
</main>
);
}
export default App;
import {
PaymentElement
} from '#stripe/react-stripe-js'
import React, {useState} from 'react'
import {useStripe, useElements} from '#stripe/react-stripe-js';
export default function CheckoutForm() {
const stripe = useStripe();
const elements = useElements();
const [message, setMessage] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
if (!stripe || !elements) {
return;
}
setIsLoading(true);
const { error } = await stripe.confirmPayment({
elements,
confirmParams: {
// Make sure to change this to your payment completion page
return_url: "http://localhost:8888",
},
});
if (error.type === "card_error" || error.type === "validation_error") {
setMessage(error.message);
} else {
setMessage("An unexpected error occured.");
}
setIsLoading(false);
}
return (
<form id="payment-form" onSubmit={handleSubmit}>
<PaymentElement id="payment-element" />
<button disabled={isLoading || !stripe || !elements} id="submit">
<span id="button-text">
{isLoading ? <div className="spinner" id="spinner"></div> : "Pay now"}
</span>
</button>
{message && <div id="payment-message">{message}</div>}
</form>
)
}
Can't seem to find any ref's to this issue on here or stripes documentation, not sure if this is a Gatsby issue or I am just doing something wrong.
Any help is greatly appreciated
cheers
Removed node_modules and reinstalled and added import { loadStripe } from '#stripe/stripe-js/pure';
You may have installed other modules like #stripe/stripe-js but I don't think you installed the main stripe module. So run npm i stripe or yarn add stripe and the error will be fixed
Related
I am playing around the code: https://codesandbox.io/s/restless-framework-uldf4q?file=/src/App.js
import React, { Fragment } from "react";
import { gql } from "apollo-boost";
import { useQuery } from "#apollo/react-hooks";
const GET_DOG_PHOTO = gql`
query Dog($breed: String!) {
dog(breed: $breed) {
id
displayImage
}
}
`;
const breed = "dingo";
const App = () => {
const [count, setCount] = React.useState(0);
const { loading, error, data, startPolling, stopPolling } = useQuery(
GET_DOG_PHOTO,
{
variables: { breed },
onCompleted: () => {
setCount((count) => count + 1);
}
}
);
if (loading) {
return <h2>loading</h2>;
}
if (error) {
return <h2>Whoops</h2>;
}
return (
<div>
<h1> {count}</h1>
<Fragment>
<img
alt="Cute Doggo"
src={data.dog.displayImage}
style={{ height: 500, width: 500 }}
/>
<button onClick={() =>startPolling(500)}>Start</button>
<button onClick={stopPolling}>Stop</button>
</Fragment>
</div>
);
};
export default App;
In my code, I setCount to count+1 using React.useState in the onCompleted callback? why it just stop counting when polling?
so what is the mechanism here?
I can also observe that the onCompleted callback is not invoked as expected in the reproducer you provide.
In your CodeSandbox, you are using a 3-year-old deprecated version of the useQuery hook. You could migrate to the latest #apollo/client package, which will solve the issue.
See this migrated CodeSandbox: https://codesandbox.io/s/apolllo-on-completed-n9wzge
I'm trying to build a website using react, its show successfully compiled in terminal but nothing shows up when npm run start.
here's the App.js
import { useState } from 'react';
import './App.css';
import MainMint from './MainMint';
import NavBar from './NavBar';
function App() {
const [accounts, setAccounts] = useState([]);
return (
<div className="App">
<NavBar accouts={accounts} setAccounts={setAccounts} />
<MainMint accouts={accounts} setAccounts={setAccounts} />
</div>
);
}
export default App;
here's the NavBar.js
import React from 'react';
const NavBar = ({ accounts, setAccounts }) => {
const isConnected = Boolean(accounts[0]);
async function connectAccount() {
if (window.ethereum) {
const accounts = await window.ethereum.request({
method: "eth_requestAccounts",
});
setAccounts(accounts);
}
}
return (
<div>
<div>Facebook</div>
<div>Twitter</div>
<div>Email</div>
<div>About</div>
<div>Mint</div>
<div>Team</div>
{isConnected ? (
<p>Connected</p>
) : (
<button onClick={connectAccount}>Connect</button>
)}
</div>
);
};
export default NavBar;
MainMint.js
import { useState } from 'react';
import { ethers, BigNumber } from 'ethers';
import roboPunksNFT from './RoboPunksNFT.json';
const roboPunksNFTAddress = "0xE6849E3b1085562C6F2733e01A5C484754D2e823";
const MainMint = ({ accounts, setAccounts }) => {
const [mintAmount, setMintAmount] = useState(1);
const isConnected = Boolean(accounts[0]);
async function handleMint() {
if (window.ethereum) {
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract(
roboPunksNFTAddress,
roboPunksNFT.abi,
signer
);
try {
const response = await contract.mint(BigNumber.from(mintAmount));
console.log('response: ', response);
} catch (err) {
console.log("error: ", err)
}
}
}
const handleDecrement = () => {
if (mintAmount <= 1) return;
setMintAmount(mintAmount - 1)
};
const handleIncrement = () => {
if (mintAmount >= 3) return;
setMintAmount(mintAmount + 1)
};
return (
<div>
<h1>Gaint Ammar</h1>
<p>It's 2078, 120kg ammar is dead!</p>
{isConnected ? (
<div>
<div>
<button onClick={handleDecrement}>-</button>
<input type="number" value={mintAmount} />
<button onClick={handleIncrement}>+</button>
</div>
<button onClick={handleMint}>Mint Now</button>
</div>
) : (
<p>You must be connected to Mint.</p>
)}
</div>
);
};
export default MainMint;
is there any problem with
const isConnected = Boolean(accounts[0]);
its also shows
DevTools failed to load source map: Could not load content for chrome-extension://cmndjbecilbocjfkibfbifhngkdmjgog/lib/browser-polyfill.js.map: System error: net::ERR_BLOCKED_BY_CLIENT in developer mode
and some errors react-don.development.js.
I keep getting this error when I run my code Uncaught TypeError: Cannot read properties of undefined (reading 'map') I am tring to set up a Metamask which displays the users NFTS that they have purchased from OpenSea when they connect their metamask account I'll show my code to show what I have done and if anyone knows how to fix this could they post a solution code as this would be of so much help.
import { useEffect, useState } from 'react';
import './nft.css'
import NFTContainer from './NFTContainer'
export function Nft() {
const [walletAddress, setWalletAddress] = useState(null)
const [nfts, setNfts] = useState()
const connectWallet = async () => {
if (typeof window.ethereum !== 'undefined') {
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
setWalletAddress(accounts[0])
}
}
const getNftData = async () => {
if (!walletAddress) return;
const response = await fetch(`https://api.rarible.org/v0.1/items/byOwner/?owner=ETHEREUM:${walletAddress}`)
const data = await response.json()
debugger
setNfts(data.items)
}
useEffect(() => {
getNftData()
}, [walletAddress])
return (
<div className='Nft'>
<div className='text'>
Account: {walletAddress}
</div>
<button className='connect-button' onClick={connectWallet}>
Connect Wallet
</button>
<NFTContainer nfts={nfts} />
</div>
);
}
export default Nft;
import React from 'react'
import NFTCard from './NFTCard'
const NFTContainer = ({ nfts }) => {
return (
<div>
{nfts.map((nft, index) => {
return <NFTCard nft={nft} key={index} />
})}
</div>
)
}
export default NFTContainer
So when I put in the nft.meta.name I keep getting the uncaught type error and wondering as to why this error keeps appearing
import React from 'react'
const NFTCard = ({ nft }) => {
return (
<div>
{nft.meta.name}
</div>
)
}
export default NFTCard
the problem is you defined your useState like this
const [nfts, setNfts] = useState()
So if you don't define any value to your state then by default it is undefined and you can't map through undefined value, so define your state like this
import { useEffect, useState } from 'react';
import './nft.css';
import NFTContainer from './NFTContainer';
export function Nft() {
const [walletAddress, setWalletAddress] = useState(null);
const [nfts, setNfts] = useState([]);
const connectWallet = async () => {
try {
if (typeof window.ethereum !== 'undefined') {
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
setWalletAddress(accounts[0]);
}
} catch (error) {
console.log('err1==>', error);
}
};
const getNftData = async () => {
try {
if (!walletAddress) return;
const response = await fetch(`https://api.rarible.org/v0.1/items/byOwner/?owner=ETHEREUM:${walletAddress}`);
const data = await response.json();
setNfts(data.items);
} catch (error) {
console.log('err2==>', error);
}
};
useEffect(() => {
getNftData();
}, [walletAddress]);
return (
<div className='Nft'>
<div className='text'>Account: {walletAddress}</div>
<button className='connect-button' onClick={connectWallet}>
{!walletAddress ? 'Connect Wallet' : 'Wallet Connected'}
</button>
<NFTContainer nfts={nfts} />
</div>
);
}
export default Nft;
Note: Also do error handling and show loader when API is fetching data from network or from chain
You are missing the initial value here,
const [nfts, setNfts] = useState([]);
You must use the default value while using the useState()hook. If you want to apply array.map() method on state value then have to declare hook with empty array useState([]).
I was following this video ("JWTUser Sessions with ReactJS & GraphQL...") when at this time the guy destructures useParams() method from react-router-dom library.
In my case, that didn't work since I am getting this error:
This is the whole code at this point:
import React, { useState, useContext } from 'react';
import { useParams, useHistory } from 'react-router-dom';
import { useConfirmMutation } from '../gql/generated/graphql';
import { AppStateContext } from './provider';
export const Confirm: React.FC = () => {
const history = useHistory();
const { appSetAuthToken, appClearAuthToken, gqlError } = useContext(AppStateContext);
const [show, setShow] = useState(false);
const [email, setEmail] = useState('');
const [confirm] = useConfirmMutation();
const { token } = useParams();
const handleFormSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
setShow(false);
appSetAuthToken(token);
const { data } = await confirm({ variables: email });
} catch {
}
};
if (token === undefined || token === '')
return <div>Enlace de confirmación de usuario inválido</div>;
return (
<div>
<div>Página de confirmación de usuario</div>
{show ? <div>{gqlError.msg}</div> : undefined}
<form>
<div>
<input
value={email}
placeholder='Correo electrónico'
type='email'
onChange={e => { setEmail(e.target.value); }}
/>
</div>
<button type='submit'>Confirmar</button>
</form>
</div>
);
};
I have also tried the same on CodeSandbox but it works. Not sure, where is my mistake. Can you see that mistake?
useParams is generic. You need to tell typescript which params you are using by specifying the value of the generic like this: useParams<MyParams>(); In your case it is:
const { token } = useParams<{token?: string}>();
Which says that token is either a string or undefined.
Yep, typescript can't destructure generic plain objects like {}.
But any works like a charm.
const { token } = useParams() as any
I need to get a list of repositories using GitHub API, search has to work on button click and on change selectBox with licences
import React, { useState, useEffect, useCallback } from "react";
import axios from "axios";
import moment from "moment";
import { Layout } from "./../Layout";
import { List } from "./../List";
import { Loader } from "./../Loader";
import { Header } from "./../Header";
import { Search } from "./../Search";
import { Licenses } from "./../Licenses";
import "./App.css";
export const App = () => {
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [hasError, setHasError] = useState(false);
const [nameSearch, setNameSearch] = useState("");
const [license, setLicense] = useState({});
const fetchData = useCallback(async () => {
setHasError(false);
setIsLoading(true);
try {
const prevMonth = moment()
.subtract(30, "days")
.format("YYYY-MM-DD");
const licenseKey = (license && license.key) || "";
const response = await axios(
`https://api.github.com/search/repositories?q=${nameSearch}+in:name+language:javascript+created:${prevMonth}${
licenseKey ? `+license:${licenseKey}` : ""
}&sort=stars&order=desc`
);
setData(response.data.items);
} catch (error) {
setHasError(true);
setData([]);
}
setIsLoading(false);
}, [license]);
useEffect(() => {
fetchData();
}, [fetchData]);
return (
<Layout>
<Header>
<Search
handleSearchChange={setNameSearch}
nameSearch={nameSearch}
isLoading={isLoading}
onSearch={fetchData}
/>
<Licenses license={license} handleLicenseChange={setLicense} />
</Header>
<main>
{hasError && <div>Error</div>}
{isLoading ? <Loader /> : <List data={data} />}
</main>
</Layout>
);
};
First of all, I get warning
Compiled with warnings.
./src/components/App/App.js
Line 42:6: React Hook useCallback has a missing dependency: 'nameSearch'. Either include it or remove the dependency array react-hooks/exhaustive-deps
And my search is not working because nameSearch is always empty in the query string.
How to make search work?
Try adding nameSearch to the list of dependencies for useCallback:
const fetchData = useCallback(async () => {
...
}, [license, nameSearch]);
and make sure setNameSearch is actually used inside Search.js so that it will have a value.