4

How to pass data from the server component to the client component in Next.js 13 app router?

I am calling an external API in page.tsx which gives the city of the person. I want to pass this city to the client component where this city can be displayed and changed. What will be the best way to achieve this? In React we can use redux but since this is next.js 13 server component not sure how to do it.

app/page.tsx

const Page = async () => {
  const city = await getCity();

  const hotels = await getHotelsByCity({
    city: city,
  });

  return (
    <div className="pt-24 md:pt-28 flex md:flex-row md:flex-wrap flex-col">
      {hotels &&
        hotels.map((hotel) => {
          <div>{hotel}</div>;
        })}
    </div>
  );
};

export default Page;

app/components/Navbar/Location.tsx

"use client";

import useSelectLocationModal from "@/app/hooks/useSelectLocationModal";

export default function Location() {
  const selectLocationModal = useSelectLocationModal();

  return (
    <div
      className="flex items-center cursor-pointer"
      onClick={() => selectLocationModal.onOpen()}
    >
      <p>{city}</p> 

    </div>
  );
}
Jonas
  • 121,568
  • 97
  • 310
  • 388
Vishal Pawar
  • 43
  • 1
  • 5

1 Answers1

2

You can pass the data as props, you just need to make sure that it is serialized .

for instance


export default async function Home() {

    let data;
    console.log("fetching data");
    try{
        const res = await fetch(process.env.API_URL + '/endpoint', {
            headers: {
                'Accept': 'application/json'
            },
            next: {
                tags: ['homepage']
            }
        });
        data = await res.json();
    }
    catch (e) {
        console.log(e);
    }

    return (
        <main>
            <YourClientComponent data={data}/>
        </main>
    )
}
Guerrilla
  • 13,375
  • 31
  • 109
  • 210
  • Actually, the Location component is not a child component. To implement above solution I need to call the API in RootLayout and then need to pass it down to Location component by props drilling. Is there any other solution to do it a better way? – Vishal Pawar Jun 13 '23 at 07:27
  • You can also use a context api ( to avoid props drilling) – Marzuk Rahman Adi Jun 25 '23 at 02:52