Next.js Discord

Discord Forum

How to get data using swr based on the id in app router?

Answered
Rex posted this in #help-forum
Open in Discord
RexOP
I am trying to get event details based on the id of event. I am using swr for fetching data in my next app.
How can I pass data to the API route and then retrieve it in teh routes file.

Here are sample code
  const { data, error, isLoading } = useSWR(
    `/api/displayevent?id=${eventId}`,
    fetcher
  );

export const fetcher = (...args) => fetch(...args).then((res) => res.json());

I am getting error for the above code. My api route is /api/displayevent
Answered by Rex
I have it working. Thanks
View full answer

10 Replies

You would probably need complete route for that(meaning including the domain)
Also you need to include the error you are getting
RexOP
this doesn't make any sense
can you please elaborate on the creation of specific route for fetching the data for specific event.
How will I create route for specific id of event?
right now I have app>api>events>route.js in netx js
this is the url being created
http://localhost:3000/api/displayevent/,65620b3b5632bf5ba57d9e41?id=undefined
for the following code
  const { data, error, isLoading } = useSWR(
    [`/api/displayevent/`, eventId],
    fetcherWithId
  );
  console.log("data: ", data);

// other file 
export const fetcherWithId = (url, eventId) =>
  fetch(`${url}?id=${eventId}`).then((r) => r.json());
RexOP
I have it working. Thanks
Answer