Next.js Discord

Discord Forum

Trying to execute server action each time page is refreshed

Answered
Sphecid wasp posted this in #help-forum
Open in Discord
Sphecid waspOP
I'm trying to execute a server action in the main page by just calling it inline in the component to count the number of times the page is loaded but it seems like the page is being cached and thus the server action is only executing if I redeploy or wait for the cache to expire. What's the correct way to go about doing this since the user isn't clicking any buttons?
Answered by ᴉuɐpɹɐɐ
useEffect [], then await server action
View full answer

22 Replies

useEffect [], then await server action
Answer
Sphecid waspOP
Ah, okay. So put it in a client component?
yep
did you put it in a server component... ? 🫠
sure you can do that but ideally GET request shouldnt do server mutation
Sphecid waspOP
Yep 🙂
Is it making a get request? I would have assumed that the server action is happening on the server when the request to / is made.
no, your initial page "refresh" is make GET request
page rendering shouldnt do mutation
putting it in client component makes more sense coz its a sideeffect of the page rendering
Sphecid waspOP
How would you implement a "page counter"?
Oh I get it.
That makes sense.
after page has loaded, user has seen the page, then run useEffect(()=>{}, [])
useEffect(() => {
  const incrementCount = async () => {
    await serverAction_incrementCount()
  }
  incrementCount()
}, [])
lucky you its a simple code
Sphecid waspOP
Got it. Just pushed the code, I'll let you know how it goes.
Yep, that worked great. Thanks 🙂
Is the POST request I see in the browser the server action happening?
glad it worked
all server action are POST