Next.js Discord

Discord Forum

client side with server side fetch

Answered
Perdonium posted this in #help-forum
Open in Discord
Hey everyone 🙂 I'm currently trying to understand client side/server side components. Can a server side page contains client side component? In that case, is it possible to pre-fetch the data used for the client side component on the server side? for example a json list
Answered by Arinji
hii, ok so a server component can have a client component in it
View full answer

23 Replies

hii, ok so a server component can have a client component in it
Answer
for data fetching, you basically have a server page to fetch data, then you pass it as props to all the components in it
An example
import { getSpotifyData } from "@/lib/functions/getSpotifyData";
import { Wrapper } from "./wrapper";

export default async function Spotify() {
  const spotifyData = await getSpotifyData();

  let spotifyTrack =
    spotifyData.trackId!.length > 0
      ? spotifyData.trackId
      : "18XlJEroUwFo0tLZxscgXE";

  return (
    <div className="flex h-fit min-h-[calc(100svh-90px)] w-full flex-col items-center justify-start">
      <div className="mt-10 flex h-full w-[90%] flex-col items-center justify-center gap-4 md:w-[90%] md:max-w-[1167px]">
        <Wrapper serverID={spotifyTrack!} serverMode={spotifyData.mode!} />
      </div>
    </div>
  );
}
i fetch the data, then pass it down to a client component cause i have shared state in the page
Hi! Thanks for answering! So the client side has no notion of getSpotifyData() and the API inside it?
nope
Well that's really helpful, thanks for answering and with the code, even clearer 🙂
No worries, if you need more ideas to fetch and pass data feel free to dm me :D
May I ask what do the ! at the end of your variable means?
thats typescript, the type for it is SpotifyData or Undefined
let spotifyTrack =
spotifyData.trackId!.length > 0
? spotifyData.trackId
: "18XlJEroUwFo0tLZxscgXE";
since i have this, im sure its never undefined
so i added ! to tell it thats itss never undefined now
Oh right, I use js right now so not using that :p
no worries lol
Thanks again for the help 🙂
btw since your new here, right click on my answer
and then click apps
and mark it as answer
Wow that's so nice lol
I'm sure I'll come back again anyway, Next seems awesome but so many questions
no worries, check out their docs
its awesome