Next.js Discord

Discord Forum

Client side component's variable transfer to API Route File

Unanswered
SpywarePerseus posted this in #help-forum
Open in Discord
Hello everyone!

Was wondering if someone can help me...

I am creating a website to sell courses and there I am integrating a payment system with stripe

So, there is a component I have components/Courses.tsx and there is a variable named courseId

And there is a api route app/api/stripe/route.js, Now i want to transfer the courseId data to the api route file, Can anyone help to do that? I am using axios for data fetching...

11 Replies

Define an async function at some place like app/actions/getCourseById
And call it from your server component
await the results & finally pass it as props to a client component to render
Should I share my code for more clarity?
Yes please
Okay wait
courses.tsx
import { NextRequest, NextResponse } from "next/server";

import prismadb from "@/lib/prismadb";
import { stripe } from "@/lib/stripe";
import { absoluteUrl } from "@/lib/utils";
import { courseIdentity } from "@/components/Courses";

const settingsUrl = absoluteUrl("/dashboard");

interface RouteProps {
    params: {
        courseId: string;
    }
}

export async function GET() {
try {
    const { userId } = auth();
    const user = await currentUser();
    const courseId = courseIdentity;

    const courseData = await prismadb.courses.findFirst({
        where: {
            id: courseId,
        }
    })

    const priceOfItem = courseData?.price * 100 + 99;

    if (!courseId) {
        return new NextResponse("Course ID is required", { status: 400 });
    }

    if (!userId || !user) {
        return new NextResponse("Unauthorized", { status: 401 });
    }

    const stripeSession = await stripe.checkout.sessions.create({
        success_url: settingsUrl,
        cancel_url: settingsUrl,
        payment_method_types: ["card"],
        mode: "payment",
        billing_address_collection: "auto",
        customer_email: user.emailAddresses[0].emailAddress,
        line_items: [
        {
            price_data: {
                currency: "INR",
                product_data: {
                    name: String(courseData?.name),
                    description: String(courseData?.description),
                },
                unit_amount: priceOfItem,
            },
            quantity: 1,
        },
        ],
        metadata: {
            userId,
            courseId,
        },
    })

    return new NextResponse(JSON.stringify({ url: stripeSession.url }))
} catch (error) {
    console.log("[STRIPE]", error);
    return new NextResponse("Internal Error", { status: 500 });
}
};
API ROUTE FILE
@SpywarePerseus courses.tsx
the problem with this is that this is a client component & to await some data from an API, you need to make the function Course as async which should be a server component.

Then after you get the results you can pass it to client UI component as props to render it realtime
Hmm
@Suvraneel