UPDATE: Have Stripe only load on pages it's needed;

FIX: Pass proper prop through `ContentContext`;
This commit is contained in:
Chris-1010
2025-02-23 23:28:14 +00:00
parent 52a15d8691
commit 38a74e0710
4 changed files with 80 additions and 57 deletions

View File

@@ -1,63 +1,68 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import { loadStripe } from "@stripe/stripe-js"; import type { Stripe } from "@stripe/stripe-js";
import { import {
EmbeddedCheckoutProvider, EmbeddedCheckoutProvider,
EmbeddedCheckout, EmbeddedCheckout,
} from "@stripe/react-stripe-js"; } from "@stripe/react-stripe-js";
import { Navigate } from "react-router-dom";
const API_URL = import.meta.env.VITE_API_URL; //! Unsure whether this component is used/needed in the project
// export const Return: React.FC = () => {
// const [status, setStatus] = useState<string | null>(null);
// const [customerEmail, setCustomerEmail] = useState("");
// Initialize Stripe once // useEffect(() => {
const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY); // const queryString = window.location.search;
// const urlParams = new URLSearchParams(queryString);
// const sessionId = urlParams.get("session_id");
export const Return: React.FC = () => { // if (sessionId) {
const [status, setStatus] = useState<string | null>(null); // console.log("1");
const [customerEmail, setCustomerEmail] = useState(""); // fetch(`/api/session-status?session_id=${sessionId}`)
// .then((res) => res.json())
// .then((data) => {
// console.log("Response Data:", data);
// setStatus(data.status);
// setCustomerEmail(data.customer_email);
// });
// }
// }, []);
useEffect(() => { // if (status === "open") {
const queryString = window.location.search; // return <Navigate to="/checkout" />;
const urlParams = new URLSearchParams(queryString); // }
const sessionId = urlParams.get("session_id");
if (sessionId) { // if (status === "complete") {
console.log("1"); // return (
fetch(`/api/session-status?session_id=${sessionId}`) // <section id="success">
.then((res) => res.json()) // <p>
.then((data) => { // We appreciate your business! A confirmation email will be sent to{" "}
console.log("Response Data:", data); // {customerEmail}. If you have any questions, please email{" "}
setStatus(data.status); // <a href="mailto:orders@example.com">orders@example.com</a>.
setCustomerEmail(data.customer_email); // </p>
}); // </section>
} // );
}, []); // }
if (status === "open") { // return null;
return <Navigate to="/checkout" />; // };
}
if (status === "complete") {
return (
<section id="success">
<p>
We appreciate your business! A confirmation email will be sent to{" "}
{customerEmail}. If you have any questions, please email{" "}
<a href="mailto:orders@example.com">orders@example.com</a>.
</p>
</section>
);
}
return null;
};
// Main CheckoutForm component
interface CheckoutFormProps { interface CheckoutFormProps {
streamerID: number; streamerID: number;
onClose: () => void; onClose: () => void;
} }
const CheckoutForm: React.FC<CheckoutFormProps> = ({ onClose, streamerID }) => { const CheckoutForm: React.FC<CheckoutFormProps> = ({ streamerID, onClose }) => {
const [stripePromise, setStripePromise] =
useState<Promise<Stripe | null> | null>(null);
useEffect(() => {
const initializeStripe = async () => {
const { loadStripe } = await import("@stripe/stripe-js");
setStripePromise(loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY));
};
initializeStripe();
}, []);
const fetchClientSecret = () => { const fetchClientSecret = () => {
return fetch(`/api/create-checkout-session?streamer_id=${streamerID}`, { return fetch(`/api/create-checkout-session?streamer_id=${streamerID}`, {
method: "POST", method: "POST",

View File

@@ -11,7 +11,7 @@ interface Item {
interface StreamItem extends Item { interface StreamItem extends Item {
type: "stream"; type: "stream";
streamer: string; username: string;
streamCategory: string; streamCategory: string;
} }
@@ -56,7 +56,7 @@ export function ContentProvider({ children }: { children: React.ReactNode }) {
type: "stream", type: "stream",
id: stream.user_id, id: stream.user_id,
title: stream.title, title: stream.title,
streamer: stream.username, username: stream.username,
streamCategory: stream.category_name, streamCategory: stream.category_name,
viewers: stream.num_viewers, viewers: stream.num_viewers,
thumbnail: thumbnail:

View File

@@ -49,7 +49,7 @@ const CategoryPage: React.FC = () => {
setStreamOffset((prev) => prev + data.length); setStreamOffset((prev) => prev + data.length);
const processedStreams = data.map((stream: any) => ({ const processedStreams: StreamData[] = data.map((stream: any) => ({
type: "stream", type: "stream",
id: stream.user_id, id: stream.user_id,
title: stream.title, title: stream.title,
@@ -80,9 +80,10 @@ const CategoryPage: React.FC = () => {
const logOnScroll = async () => { const logOnScroll = async () => {
if (hasMoreData && listRowRef.current) { if (hasMoreData && listRowRef.current) {
const newCategories = await fetchCategoryStreams(); const newCategories = await fetchCategoryStreams();
if (newCategories?.length > 0) { if (newCategories && newCategories.length > 0) {
listRowRef.current.addMoreItems(newCategories); listRowRef.current.addMoreItems(newCategories);
} }
else console.log("No more data to fetch");
} }
}; };

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect, lazy, Suspense } from "react";
import { ToggleButton } from "../components/Input/Button"; import { ToggleButton } from "../components/Input/Button";
import ChatPanel from "../components/Stream/ChatPanel"; import ChatPanel from "../components/Stream/ChatPanel";
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
@@ -8,10 +8,12 @@ import { useFollow } from "../hooks/useFollow";
import VideoPlayer from "../components/Stream/VideoPlayer"; import VideoPlayer from "../components/Stream/VideoPlayer";
import { SocketProvider } from "../context/SocketContext"; import { SocketProvider } from "../context/SocketContext";
import AuthModal from "../components/Auth/AuthModal"; import AuthModal from "../components/Auth/AuthModal";
import CheckoutForm, { Return } from "../components/Checkout/CheckoutForm";
import DynamicPageContent from "../components/Layout/DynamicPageContent"; import DynamicPageContent from "../components/Layout/DynamicPageContent";
import { useSidebar } from "../context/SidebarContext"; import { useSidebar } from "../context/SidebarContext";
// Lazy load the CheckoutForm component
const CheckoutForm = lazy(() => import("../components/Checkout/CheckoutForm"));
interface VideoPageProps { interface VideoPageProps {
streamerId: number; streamerId: number;
} }
@@ -33,6 +35,7 @@ const VideoPage: React.FC<VideoPageProps> = ({ streamerId }) => {
const { isFollowing, checkFollowStatus, followUser, unfollowUser } = const { isFollowing, checkFollowStatus, followUser, unfollowUser } =
useFollow(); useFollow();
const { showAuthModal, setShowAuthModal } = useAuthModal(); const { showAuthModal, setShowAuthModal } = useAuthModal();
const [isStripeReady, setIsStripeReady] = useState(false);
const [showCheckout, setShowCheckout] = useState(false); const [showCheckout, setShowCheckout] = useState(false);
const showReturn = window.location.search.includes("session_id"); const showReturn = window.location.search.includes("session_id");
const navigate = useNavigate(); const navigate = useNavigate();
@@ -107,6 +110,15 @@ const VideoPage: React.FC<VideoPageProps> = ({ streamerId }) => {
}; };
}, []); }, []);
// Load Stripe in the background when component mounts
useEffect(() => {
const loadStripe = async () => {
await import("@stripe/stripe-js");
setIsStripeReady(true);
};
loadStripe();
}, []);
const toggleChat = () => { const toggleChat = () => {
setIsChatOpen((prev) => !prev); setIsChatOpen((prev) => !prev);
}; };
@@ -235,26 +247,31 @@ const VideoPage: React.FC<VideoPageProps> = ({ streamerId }) => {
{/* Subscribe Button */} {/* Subscribe Button */}
<div className="flex flex-col items-center"> <div className="flex flex-col items-center">
<button <button
className="bg-red-600 text-white font-bold px-[1.5em] py-[0.5em] rounded-md hover:bg-red-700 text-sm" className={`bg-red-600 text-white font-bold px-[1.5em] py-[0.5em] rounded-md
${
isStripeReady ? "hover:bg-red-700" : "opacity-20 cursor-not-allowed"
} transition-all`}
onClick={() => { onClick={() => {
if (!isLoggedIn) { if (!isLoggedIn) {
setShowAuthModal(true); setShowAuthModal(true);
} else { } else if (isStripeReady) {
setShowCheckout(true); setShowCheckout(true);
} }
}} }}
> >
Subscribe {isStripeReady ? "Subscribe" : "Loading..."}
</button> </button>
</div> </div>
</div> </div>
{showCheckout && ( {showCheckout && (
<CheckoutForm <Suspense fallback={<div>Loading checkout...</div>}>
onClose={() => setShowCheckout(false)} <CheckoutForm
streamerID={streamerId} onClose={() => setShowCheckout(false)}
/> streamerID={streamerId}
/>
</Suspense>
)} )}
{showReturn && <Return />} {/* {showReturn && <Return />} */}
{showAuthModal && ( {showAuthModal && (
<AuthModal onClose={() => setShowAuthModal(false)} /> <AuthModal onClose={() => setShowAuthModal(false)} />
)} )}