So I am calling an API inside Metadata
to fetch details on the URL entered. To access the URL, I am using next/headers
.
export async function generateMetadata(
{ params, searchParams }: MetadataProps,
parent: ResolvingMetadata
): Promise<Metadata> {
// read route params
const id = params.id;
const headersList = headers();
const domain = headersList.get("x-forwarded-host") || "localhost:3000"; // get url
// fetch data
const hotelAuth = await fetch(
`apidomain.com/parameter/[url-of-the-website]`,
{ next: { revalidate: 3600 } }
).then((res) => res.json());
return {
title: hotelAuth?.data?.hotel_name,
description: hotelAuth?.data?.hotel_description,
openGraph: {
title: hotelAuth?.data?.hotel_name,
description: hotelAuth?.data?.hotel_description,
},
};
}
I want to access the domain
variable in other component or possibly store the hotelAuth
response in zustand.
I tried creating a custom hook for making the api call second time but I still need to access the URL.
"use client";
import { useEffect } from 'react';
import useSWR from "swr";
import apiEndpoints from "./endpoints";
import getResponse from "./getResponse";
export const useHotelAuth = () => {
const { auth } = apiEndpoints.GET;
useEffect(()=>{
if (typeof window !== 'undefined'){
console.log(window.location.href)
}
}, [window])
const { data, isLoading, error } = useSWR(`apiEnpoint/[url-of-the-current-site]`, getResponse);
return { hotelAuthData: data, hotelAuthLoading: isLoading, error };
};
and this gives error as: window is not defined
So how can I get the URL in the client side and how can I pass data from the server side component to client side or store in zustand.
The problem appears to revolve around how you incorporate the window
parameter within the useEffect
dependency array.
useEffect(() => {
if (typeof window !== "undefined") {
console.log(window.location.href);
}
}, []); //remove window parameter