I am using useSWR
to call the internal Nextjs API route to query the database.
const fetcher = (url: string) => axios.get(url).then((r) => console.log(r.data))
export default function Model(){
const searchParams = useSearchParams();
const selectedMatch= searchParams.get("data");
const { data } = useSWR("/api/model?data=" + selectedMatch, fetcher, {refreshInterval: 100});
return (<p>{data}</p>)}
My /api/model
:
import { connectToDB } from "@/app/utils/database";
import Events from "@/models/events";
export const GET = async (req: Object) => {
await connectToDB();
const matchString: String = req.nextUrl.searchParams.get("data")
var events: any = {};
try {
matchString.split(",").map(async (match: string) => {
events[match] = await Events.find({ name: match }).then((res) => res[0]);
});
return new Response(JSON.stringify(events), { status: 200 });
} catch (error) {
return new Response("Failed to fetch all events", { status: 500 });
}
};
However, when I do the axios.get(url).then((r) => console.log(r.data))
, it logs the empty object {}
, if I console.log the JSON.stringify(events)
in /api/model
before the return, it does give me the correct data from the database, may I ask why?