I am using useSWR
in nextjs, the API endpoint is calling the database async query in api route.
const fetcher = (url: string) => axios.get(url).then((r) => r.data);
const { data, error } = useSWR("/api/model?data=" + selectedMatch, fetcher, {
refreshInterval: 1000,
});
Then console.log(data)
afterward, the object does log:
console.log(data)
console.log(typeof(data))
However when I add console.log(Object.keys(data))
after these two lines of code, this error suddenly come out, and the typeof(data)
become undefined.
I tried to change useSWR
to useSWRImmutable
, because I think useSWR
might keep changing data
while I try to fetch, but it doesn't work.
Cannot convert undefined or null to object
The endpoint that refers to the database query is something like this:
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 });
};
May I ask why and where's the problem?