Next.js Discord

Discord Forum

usePathname in server component?

Answered
Waterman posted this in #help-forum
Open in Discord
Avatar
Hello! I want to fetch some data from a database, the data is a product

The product has an id that I want to access with usePathname and in a client component this would work fine but the problem is that I want to use a server component to be able to fetch data live without having to rebuild app everytime I make changes to my admin panel.

So my question is, can I get this id from the url any other way?
the url could look something like this:
http://localhost:3000/kollektioner/artistic-glimmer

^^^ More like a name but I'll call it an Id

I appreciate all help, thanks 🙂

Code:

import { usePathname } from "next/navigation";
 
export default async function Page() {
  const pathname = usePathname();
  const parts = pathname.split("/");
  const id = parts[parts.length - 1];

  const data = await fetch("/api/basproduct?id=" + id).then((response) => {
    console.log("data" + data);
    console.log("response" + response);
  });

  return (
    <main className="min-h-screen text-center w-full">
      <section className="flex w-full">
        <div className="w-full">
          <h1 className="text-center py-40 w-full">Kommer Snart!</h1>
          <div></div>
        </div>
        <div>
          <h1></h1>
        </div>
      </section>
    </main>
  );
}
Answered by Waterman
how I did it:
import { headers } from "next/headers";
import axios from "axios";

export default async function Page() {
  const headersList = headers();
  const domain = headersList.get("host") || "";
  const fullUrl = headersList.get("referer") || "";
  const parts = fullUrl.split("/");
  const id = parts[parts.length - 1];

  const response = await fetch(`${process.env.HOST}/api/basproduct?id=` + id);
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  } else {
    const data = await response.json();
    console.log(data);
  }

more code...
View full answer

1 Reply

Avatar
how I did it:
import { headers } from "next/headers";
import axios from "axios";

export default async function Page() {
  const headersList = headers();
  const domain = headersList.get("host") || "";
  const fullUrl = headersList.get("referer") || "";
  const parts = fullUrl.split("/");
  const id = parts[parts.length - 1];

  const response = await fetch(`${process.env.HOST}/api/basproduct?id=` + id);
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  } else {
    const data = await response.json();
    console.log(data);
  }

more code...
Answer