0

I am calling the internal API route by passing the searchParams to search the database (api/model/route.js):

import { connectToDB } from "@/app/utils/database";
import Events from "@/models/events";
import { NextRequest } from "next/server";

export const GET = async (req: NextRequest) => {
  await connectToDB();
  const matchString: String = req.nextUrl.searchParams.get("data") || "[]"
  const events: any = {};
  const promises = matchString.split(",").map(async (match: string) => {
    try {
      events[match] = await Events.find({ name: match }).then((res) => res[0]);
    } catch (error) {
      events[match] = error;
      console.log("model/route.js error")
    }
  })

  await Promise.all(promises)
  return new Response(JSON.stringify(events), { status: 200 });
};

I am trying to use GetServerSideProps to do:

await fetch("/api/model?data=" + searchParams.data)

However, searchParams is not at getServerSideProps, instead it's inside the Page function:

export default async function Page({
  searchParams,
}: {
  searchParams: SearchParams;
}) {
  const selectedMatch = searchParams.data || "[]";
...

so how can I fetch the database at request time? I want to base on the result to initialise my useState object.

TungTung
  • 163
  • 7

0 Answers0