Store data from server-side in client
Answered
Flemish Giant posted this in #help-forum
Flemish GiantOP
What’s the best way to store data from server in client?
I have this code that works, but it feels very hacky.
I have this code that works, but it feels very hacky.
// /app/page.jsx
export default async function Home() {
const session = …;
const user = await fetchUser(session);
return (
<div>
<StateInitializer user={user} />
…
</div>
);
}
// /app/state-initializer.jsx
"use client";
// Initialize zustand global state
export function StateInitializer({ user }: { user: UserData }) {
const setUser = useUserStore((state) => state.setUser);
setUser(user);
return null;
}
Answered by Siberian
I think creators of Next.js intended to have it this way, so You can get all stuff you need at Server, pass it to client and then either use it everywhere you need to, or pass it to some state or store and hold it right there
11 Replies
Flemish GiantOP
Also I prefer to keep
page.jsx
server componentSiberian
Well. If you want to keep user on server side. You need to pass it in props exactly how you doing. And then you do with that data whatever you want to (without mutating props)
Flemish GiantOP
No, I want to fetch user from external source (server-side), and then store it globally in client-side (zustand)
This is what I’d do in Next.js v12
export default function Home({ user }) {
const setUser = useUserStore((state) => state.setUser); // << this has to be called in client context
setUser(user);
return (
<div>
…
</div>
);
}
export async function getServerSideProps(ctx) {
const session = …;
const user = await fetchUser(session);
return { props: { user } };
}
I think the hacky feeling comes from that I have to create meaningless component to invoke JS code client side
Siberian
I think creators of Next.js intended to have it this way, so You can get all stuff you need at Server, pass it to client and then either use it everywhere you need to, or pass it to some state or store and hold it right there
Answer
Flemish GiantOP
Hmm if it’s the best, I understand
Thank you 😊
Siberian
Personally I would still prefer to use just whatever details I get from server and use it around without storing it anywhere else
Flemish GiantOP
Yeah.. maybe I should more rely on Request Memorization / Data Cache
joulev
SaaikaHatak was correct. The code in the question is completely fine and is what you are supposed to do