Next.js Discord

Discord Forum

Get route/path in an async function but not in getserversideprops

Answered
Say's Phoebe posted this in #help-forum
Open in Discord
Say's PhoebeOP
I want to get the current route/path in an export default async function and want to send the data accordingly

5 Replies

Say's PhoebeOP
import { usePathname } from "next/navigation"; 

export default async function Page() {
  const data = await getData();
  const current_route = usePathname(); // I can't get the data here because of the error that "use client" is required. But I can't use client because export default function is async
  const compiled_data = (<>

  </>
)

}

async function getData() {
  const res = await fetch(
    "https://raw.githubusercontent.com/lite-xl/lite-xl-colors/master/manifest.json"
  );

  if (!res.ok) {
    throw new Error("Failed to fetch data");
  }
  return res.json();
}
Answer
Say's PhoebeOP
Oh! wow thats working:
I have made the following modifications:
export default async function Page({
  params,
}: {
  params: { slug: string }
}) {
  const data = await getData();
  return <h1>{params.slug}</h1>
}

async function getData() {
  const res = await fetch(
    "https://raw.githubusercontent.com/lite-xl/lite-xl-colors/master/manifest.json"
  );

  if (!res.ok) {
    throw new Error("Failed to fetch data");
  }
  return res.json();
}
You’re welcome