#What's the best way to fetch data on server components? (between these two options)

14 messages · Page 1 of 1 (latest)

random sail
#
export default async function Home() {
  // fetching data directly into the database
  const posts = await prisma.post.findMany();

  // fetching data from a nextJs api endpoint that will fetch my database
  const { posts } = await fetch('/api/posts')

  return (
    <main>
      <AddPost />
      {posts.map((post, key) => (
        <Post {...post} key={`post_${key}`} />
      ))}
    </main>
  );
}

I really prefer to fetch the database directly, but won't that disable the next fetch cache behavior?
The database query was the correct way to handle this on the /pages getServerSideProps, it feels wrong to run a request from NextJs to NextJs at component build time

random sail
#

I think the ideal way would be to query from the database initially, and update the content through an api once necessary. is it possible?

viral locust
#

you can still cache the prisma findmany by using cache()

#

if you are doing the second one, you are literally fetching to your own server

random sail
viral locust
random sail
#

I mean, once a user adds a new post, it should be displayed

viral locust
#

ah im not sure how to revalidate it in server-side to update the data. I haven't found the answer myself. But I what i used is a client query tool like react-query to update the data client-side

random sail
#

Gonna try to learn this then

random sail
#

I can literally just use router.refresh() and query stuff directly into the database, I love this thing new version.

fickle merlin
#

@random sail Did you end up going with the direct database access? I'm currently in this situation now

random sail
fickle merlin
#

Awesome, thanks so much!