Next.js Discord

Discord Forum

Properly call a function and send props

Unanswered
Sirex woodwasp posted this in #help-forum
Open in Discord
Sirex woodwaspOP
Hello everyone!

I honestly cannot find any solid information nor examples of my exact issue. Maybe I'm searching incorrectly? I don't know. So far nobody has been able to help yet.

As you might know, you can send props from a Server component to a Client component. But I need it the other way around. I have data in my Client component that I need to send to the Server component.

Next to that, I also want to call a function in a Server component from the client.

Let's say I have a fetch on the Server component, and the moment a user clicks on a button, let's call this "Fetch Data", it will run the function in the Server component called "getData", like this example:
async function getData() {
  const res = await fetch('https://api.example.com/${userId}')
  if (!res.ok) {
    throw new Error('Failed to fetch data')
  }
  return res.json()
}


Now I have a fetch on my server component, and a "fetch data" button on my client component with a specific prop, let's call this "userId", where it would fetch the url https://api.example.com/${userId}.

This would
1. send the userId prop to the server component
2. call the getData function, with the prop to fetch the component using the Server, for the sensitive data.

Is this even possible? If so, how? I am genuine lost on this and I don't know where to look further. There is little to none documentation, or it's not understandable for less advanced users, like me.

Any help and/or examples are appreciated!

6 Replies

@Giant panda https://nextjs-faq.com/sharing-client-side-state-with-server-components
Sirex woodwaspOP
Thanks for this!
However, I think this only explains part of the question, which is the first, how to send a prop to the server, but what about the second?

- call the getData function, with the prop to fetch the component using the Server, for the sensitive data.
Sirex woodwaspOP
Even though I have to say, I think it's still very much not documented at all and using searchParams seems like a bad way to do so.
Like, what if you want to make a PUT request on the server, but only after the user pressed a button?

I don't want the server component to automatically run the fetch on page load, I want it to run the moment the user presses something which triggers the function.
Giant panda
Using search params is the most idiomatic way for fetching different data that should be displayed, e.g. when filtering etc.. Think of it as a response to a GET request.
If you want a mutation, i.e. a POST/PUT/DELETE request so to speak, you'd use a server actions or a route handler that you invoke normally.
Basic JS unrelated to Next.