i decided to use nextjs with stripe and did it like this, but i get the error Error: Please pass a valid Stripe object to StripeProvider. You can obtain a Stripe object by calling 'Stripe(...)' with your publishable key.
i am passing a stripe object but weirdly enough it doesnt go through and even when trying to console.log in next.js its not showing in console. So what am i doing wrong? Thanks
function MyApp({ Component, pageProps }) {
const [stripe, setStripe] = useState({ stripe: null });
useEffect(() => {
console.log("djdsjdjsd");
if (window.Stripe) {
setStripe({ stripe: window.Stripe('pk_test') });
} else {
document.querySelector('#stripe-js').addEventListener('load', () => {
// Create Stripe instance once Stripe.js loads
setStripe({ stripe: window.Stripe('pk_test') });
});
}
}, []);
return (
<>
<Head>
<title>My page title</title>
<meta property="og:title" content="My page title" key="title" />
<script async src="https://js.stripe.com/v3/"></script>
</Head>
<StripeProvider stripe={stripe}>
<Component {...pageProps} />
</StripeProvider>
</>
)
}
Instead of trying to build your component around Stripe.js loading like this, you should use the loadStripe helper from #stripe/stripe-js with the Elements provider from #stripe/react-stripe-js. This will handle loading Stripe.js for you asynchronously along with the initialization.
Docs
Example:
import {Elements} from '#stripe/react-stripe-js';
import {loadStripe} from '#stripe/stripe-js';
const stripePromise = loadStripe('pk_test_123');
const App = () => {
return (
<Elements stripe={stripePromise}>
<PaymentComponentWithCardElementEtc />
</Elements>
);
};
Related
I'm trying to fetch data from the server side using SSR. unfortunately the initial loading time is awful, around 6s.
i tried to use both getServerSideProps and getStaticProps. however, the results remains the same.
it there a way to bypass that or to call the API from the FE would suit the situation better?
import Head from 'next/head';
import { useQuery } from 'react-query';
import { getCountries } from '../infrastructure/http/client';
import { Navbar } from '#/components/navbar/navbar';
import { FilterSection } from '#/components/filter-section/filter-section';
import { CardsSection } from '#/components/cards-section/cards-section';
import { Store } from '#/state/store';
export async function getServerSideProps(context : any) {
const getCountriesData = await getCountries();
const countriesData = await JSON.parse(getCountriesData);
return {
props: {
countriesData,
},
};
};
// Maybe i dont need an api call for the entire page, will try to move it to the
// store
export default function Home({countriesData} : any) {
// pass the data received from getServerSideProps
const { data } = useQuery('todos', getCountries, { initialData: countriesData });
console.log(data);
return (
<>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Navbar />
<Store >
{/* TODO ---- */}
{/* Routing */}
<FilterSection />
<CardsSection countriesData={countriesData} />
</Store>
</>
);
};
This question already has answers here:
React 18: Hydration failed because the initial UI does not match what was rendered on the server
(43 answers)
Closed 4 months ago.
My getstaticProps:
export async function getStaticProps({ params }) {
const mainMenuData = await fetch(
`https://example.com/get/main-menu`
).then((res) => res.json());
return {
props: {
mainMenuData,
},
revalidate: 60,
};
}
Using the component:
<Header data={mainMenuData} />
My component:
export default function Header({ data }) {
return (
<>
{data.main_menu}
</>
);
}
The data is an object, and I can access it so technically I know it's possible. However when I start mapping through the data I keep getting the error:
Hydration failed because the initial UI does not match what was rendered on the server
I'm new to Next and I'm not sure this method is correct.
Edit: Page component
import Head from "next/head";
import styles from "../styles/Home.module.css";
import Header from "../components/header";
export default function Page({ mainMenuData }) {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<Header data={mainMenuData} />
</main>
</div>
);
}
export async function getStaticProps({ params }) {
const mainMenuData = await fetch(
`https://example.com/get/main-menu`
).then((res) => res.json());
return {
props: {
mainMenuData,
},
revalidate: 60,
};
}
This error might be happening due to not wrapping the data you are passing to Header properly in a JSX element. Try using a JSX element inside of Header like a div or ul if it's a list for example.
Also, avoid some JSX wrapping patterns such as, for example, a p tag wrapping up a div, section, etc. Next.js will most likely throw a similar error because of this.
Reference thread
Despite having seen working examples of this in non remix projects, it doesn't seem to work in the way I'm implementing it?
I have the following in root.tsx:
export const MyContext = createContext("default");
function Document({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<Meta />
<Links />
</head>
<body className="root-body">
<MyContext.Provider value="bonjour!">
<Header />
</MyContext.Provider>
{children}
<ScrollRestoration />
<Scripts />
<LiveReload />
<Footer />
</body>
</html>
);
}
export default function App() {
return (
<Document>
<Outlet />
</Document>
);
}
In my <Header/> component I have:
import { useContext } from "react";
import { MyContext } from "~/root";
export const Header = () => {
const result = useContext(MyContext);
console.log(result);
return(null)
}
The result is then that "default" is printed to the console, but surely from my understanding it should be "bonjour"?
Where am I going wrong?
The output on the server console is from Remix SSR. It does appear that the context is not being applied during server rendering. However, it does show up correctly after hydration. Unfortunately it also results in hydration errors (see browser console).
Anyway, that does seem odd. My understanding is that you can use most hooks server side (except for useEffect and useLayoutEffect).
https://codesandbox.io/s/remix-react-context-mzexmt
I have been using react storefront for a couple of weeks now. Though I understood high level concepts, I am really stuck for API implementation using fulfillAPIRequest, fetchFromAPI, appData and pageData etc.
My current code is as follows:
File: _app.js:
export default function MyApp({ Component, pageProps }) {
useJssStyles()
const classes = useStyles()
const [appData] = useAppStore(pageProps || {})
return (
<PWA errorReporter={reportError}>
<Head>
{/* <meta
key="viewport"
name="viewport"
content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
/> */}
</Head>
<SessionProvider url="/api/session">
<MuiThemeProvider theme={theme}>
<CssBaseline/>
<Header className={classes.header} />
<HeaderBanner />
<Delivery />
<Search />
<main className={classes.main}>
<Component {...pageProps} />
</main>
<Footer />
</MuiThemeProvider>
</SessionProvider>
</PWA>
)
}
MyApp.getInitialProps = async function({ Component, ctx }) {
let pageProps = {}
if (Component.getInitialProps) {
console.info("Executing _app.js: Invoking Component.getInitialProps...")
pageProps = await Component.getInitialProps(ctx)
}
return { pageProps }
}
file: pages/index.js => entry point page
import React from 'react'
import { fetchFromAPI, createLazyProps } from 'react-storefront/props'
import NearbyShops from '../components/shops/nearby-shops.js'
export default function Index(lazyProps) {
return (
<NearbyShops />
)
}
Index.getInitialProps = createLazyProps(fetchFromAPI, { timeout: 50 })
I implemented api for the page index.js, in the foder /pages/api/index.js, as follows...
import fulfillApiRequest from 'react-storefront/props/fulfillAPIRequest'
function getPageData () {
console.info("Executing 'getPageData' in /api/index.js...")
return Promise.resolve({})
}
export default async function Index (params, req, res) {
console.info("Executing '/pages/api/index.js' ...")
const result = await fulfillApiRequest(req, {
appData: () => getAppData(),
pageData: () => getPageData()
})
return result
}
When I run this app, I get the following error in the GUI:
In the console, I get the error stack trace as follows...
If I don't use the fulfillAPIRequest and its related api methods, I am able to show the rendered page, normally. But now I want to integrate the API. The official documentation is not that helpful in this regard.
Please help.
This is my Code Which I got from react-p5 typescript Example and modified it a bit
import Sketch from "react-p5";
import p5Types from "p5";
type InputParameterType = {};
function P5JsComponent({}: InputParameterType) {
let x = 50;
const y = 50;
//See annotations in JS for more information
const setup = (p5: p5Types, canvasParentRef: Element) => {
p5.createCanvas(500, 500).parent(canvasParentRef);
};
const draw = (p5: p5Types) => {
p5.background(0);
p5.ellipse(x, y, 70, 70);
x++;
};
return <Sketch setup={setup} draw={draw} />;
}
export default P5JsComponent;
My Parent Component in My NextJs App is 'homepage.tsx' which is present in the pages directory.
import Head from "next/head";
import P5JsComponent from "#/components/P5JsComponent";
function homepage() {
return (
<div>
<Head>
<title>My App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<P5JsComponent />
</div>
);
}
export default homepage;
I am getting a ReferenceError: window is not defined error when I run this code.
In server-side-rendering, we haven't global variables from the browser, like the "window" variable.
P5JsComponent must be rendered on the client-side.
Import P5JsComponent with no SSR:
const P5JsComponent = dynamic(
() => import("#/components/P5JsComponent"),
{ ssr: false }
)
ref: https://nextjs.org/docs/advanced-features/dynamic-import