Next.js Discord

Discord Forum

How to fetch data based on client input

Unanswered
Maine Coon posted this in #help-forum
Open in Discord
Maine CoonOP
I have a component which depends on user input.
It's a diagram which shows statistics from some data for a specific time range.
The user uses the component "DateRangePicker" to select a start and an end date.
Based on that, the diagram should display the statistics.
How should or could I do that?

The DateRangePicker is obviously a client component.
I do not use API routes but server side fetching and server actions to fetch data.

Right now it looks like this:

<Page> // Server component: fetches initial data through server action
<DateRangePicker /> // Client component with state of the current date range
<Diagram /> // Needs date range from DateRangePicker to fetch specific data
</Page>

7 Replies

from the topic description, I feel like you are thinking of having it as a server component but I think it's better to be a client component
if it's a client component no issue at all right? you have have those date ranage as a state in context or redux and make requests when they change
if your <Diagram /> is server component, you can use query params in the url to store the date range
you can get those query params in the server component and perform server-side data fetching!
Maine CoonOP
Hey @James4u , it's about the data fetching. Do I have to use API routes? Currently, I fetch the initial data through simple data = await getData() [server action] in the parent server component, which is the page. I pass that data to the diagram to display it.
But in the client component date range picker, I want to select the dates and after that, refetch the data, that's my problem right now
Maine CoonOP
Ok, I found a solution: right now, I am using a server action in the client component.
<Page>
<WrapperComponent> // client component with State
<DateSelectionComponent /> // client component which calls a server action to fetch data after selected date range has changed
<Diagram /> // client component which displays the data
</WrapperComponent>
</Page>