Replies: 2 comments 3 replies
-
you can use cookies-next library: import { cookies } from 'next/headers';
import { setCookie } from 'cookies-next';
export default function Layout({ children, params }: { children: React.ReactNode, params: { city: string } }) {
const cityParam = params?.city;
const city = cityParam || 'london';
if (cityParam) {
setCookie('city', cityParam, { maxAge: 60 * 60 * 24 * 7 });
}
return (
<html lang="en">
<body>
{children}
</body>
</html>
);
} i hope it help |
Beta Was this translation helpful? Give feedback.
1 reply
-
Hello,I think this is what you want , yes?
So here’s how you can set this up:
this is my code for your problem please check it carfully and tell me if you did not understand it import { cookies } from 'next/headers';
import { usePathname, useRouter } from 'next/navigation';
import { CityProvider } from './CityProvider';
import Header from './Header';
import Footer from './Footer';
import { getCity } from './api/getCity';
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
const cityCookie = cookies().get('city');
const cityParam = pathname.split('/').pop(); // Assuming [city] is at the end of the path
// Determine initialCity based on city param or cookie
let initialCity;
if (cityParam && cityParam !== cityCookie?.value) {
// Fetch city data based on URL param
initialCity = await getCity(cityParam);
// Set city in cookies for subsequent visits
cookies().set('city', cityParam);
} else {
// Use the cookie if there’s no city param in URL
initialCity = cityCookie?.value ? await getCity(cityCookie.value) : await getCity('london');
}
return (
<CityProvider initialCity={initialCity}>
<Header />
{children}
<Footer />
</CityProvider>
);
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Summary
Please help me! My application structure:
this my RootLayout:
I want initialCity to contain the value from cookies if there is no param [city] in the URL. And if the URL contains param [city], then the value was taken from it and written to cookies.
How can I do this? I don't want to make 2 layouts for the sake of this, I probably need to get [city] in the RootLayout.
I beg you to help me. I haven't been able to solve this problem for 2 weeks now (
Additional information
No response
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions