There's a way to run a fetch to the DB only once when the page is loaded in a server component?
Unanswered
lyingcap posted this in #help-forum
lyingcapOP
I'm trying to make a fetch to the DB to get some user information, but I want to do that only when the page loads to avoid these too many calls.
I was thinking of using useEffect, but as it is a server component there is no way to use hooks.
There's another way to do this?
I was thinking of using useEffect, but as it is a server component there is no way to use hooks.
There's another way to do this?
14 Replies
Giant panda
// This request should be refetched on every request.
// Similar to
const dynamicData = await fetch(
// Similar to
getServerSideProps.const dynamicData = await fetch(
https://..., { cache: 'no-store' })maybe you can use
fetch parameters which came from next js
this is fetching data when need to request
lyingcapOP
yes, this is exactly what is happening right now
but I'm trying to do just like I was using an useEffect
to fetch only when the component mounts
useEffect(() => {
const data = await fetch(https://..., { cache: 'no-store' })
}, [])to fetch only when the component mounts
but the use of hooks just like useEffect is allowed just in client components, and I am trying to do it in a sever component
nvm I think I found a solution in the nextjs13 docs
async function getData() {
const res = await fetch('https://api.example.com/...')
// The return value is *not* serialized
// You can return Date, Map, Set, etc.
// Recommendation: handle errors
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error('Failed to fetch data')
}
return res.json()
}
export default async function Page() {
const data = await getData()
return <main></main>
}Giant panda
yes as like you I understand. Probably u need to use if block like if(!componentExist){ do something}
but is it really neccesary use server
lyingcapOP
there's a code convention that the page must be a server component in this project that I'm working, and all the necessary data from that route must be fetched in this page and passed by props for the other components
just for this that I'm trying to do this way