How can I access a value from localStorage in a server component?
Unanswered
Pyr0Lover posted this in #help-forum
The simplest way to do this, would be to wrap it all with a "use client" but since the List component has a fetch call, so I can't...
I'm really not sure how to.
import { Locale } from '@/i18next.config';
import { getDictionary } from '@/app/lib/dictionary';
import List from '@/app/ui/list';
export default async function Page({
params: { lang },
}: {
params: { lang: Locale };
}) {
const { page } = await getDictionary(lang);
const isClient = typeof window !== 'undefined';
if (isClient) {
const ids = JSON.parse(localStorage.getItem('favorites') || '[111111]');
console.log(ids);
}
return (
<main className="my-10 flex flex-col items-center">
{isClient && (
<List
params={{ lang: lang }}
searchParams={{
ids: ids,
}}
/>
)}
<div className="mx-auto my-0 grid grid-cols-1 gap-8 md:mx-8 md:my-10 md:grid-cols-2"></div>
</main>
);
}
I'm really not sure how to.
import { Locale } from '@/i18next.config';
import { getDictionary } from '@/app/lib/dictionary';
import List from '@/app/ui/list';
export default async function Page({
params: { lang },
}: {
params: { lang: Locale };
}) {
const { page } = await getDictionary(lang);
const isClient = typeof window !== 'undefined';
if (isClient) {
const ids = JSON.parse(localStorage.getItem('favorites') || '[111111]');
console.log(ids);
}
return (
<main className="my-10 flex flex-col items-center">
{isClient && (
<List
params={{ lang: lang }}
searchParams={{
ids: ids,
}}
/>
)}
<div className="mx-auto my-0 grid grid-cols-1 gap-8 md:mx-8 md:my-10 md:grid-cols-2"></div>
</main>
);
}
5 Replies
This:
const isClient = typeof window !== 'undefined';
is useless, since currently its always server. So not sure how I can create a client component, which calls localStorage and returns the value to this page.tsx file
const isClient = typeof window !== 'undefined';
is useless, since currently its always server. So not sure how I can create a client component, which calls localStorage and returns the value to this page.tsx file
you can't access to the localstorage in server component
localStorage is a window object property, which makes it a global object that can interact with and manipulate the browser window
as you can't access to the window, you can't access to the localstorage
make it client component @Pyr0Lover