Filling client data from RSC
Unanswered
Polar bear posted this in #help-forum
Polar bearOP
Wrapped my project within a AppContext that contains all the data I need, so I don't do too many requests to the database for every change, but I could quite confusing on how to fulfill the data from RSC.
My first approach, without the Context API was just calling the database and sending down all the data I need to the client components.
Then with Context API my thought was: I don't want to send data as props, so I'll just call the database and run
My solution was to send down the data in the first time the home page is rendered as RSC, then inside the other components (let's say EpisodesSection) I receive the
What would be a better solution?
Code Example:
It reflects exactly how I'm doing right now!
My first approach, without the Context API was just calling the database and sending down all the data I need to the client components.
Then with Context API my thought was: I don't want to send data as props, so I'll just call the database and run
setEpisodes(await getEpisodesFromDatabase()) inside my RSC, then I realize that the Context API only works inside client components.My solution was to send down the data in the first time the home page is rendered as RSC, then inside the other components (let's say EpisodesSection) I receive the
episodes as props then I call setEpisodes if there's no data attached to it in the first place.What would be a better solution?
Code Example:
It reflects exactly how I'm doing right now!
// page.tsx
export default async function Home() {
const episodes = await getEpisodes();
return (
<EpisodesSection episodes={episodes} />
)
}
// episodes-section.tsx
"use client";
export const EpisodesSection = (props: { episodes: Episode[] }) => {
const { episodes, setEpisodes } = useAppContext();
if (episodes.length === 0) {
setEpisodes(props.episodes)
}
return (
<>
{episodes.map(episode => (<EpisodeComponent key={episode.id} />))}
</>
)
}