Pass state in client child component to server parent component
Answered
Broad-snouted Caiman posted this in #help-forum
Broad-snouted CaimanOP
What's the best practice to do this? For example I have a category selection child component which has "use client". It's used inside a page that is a server component. How can I pass the state of the category selection to the parent page?
24 Replies
I would use url searchParams
/?category=1Broad-snouted CaimanOP
Sure, but what about with more complex states, such as rich content from an editor?
in the client, use
router.push(/?category=${category})@Broad-snouted Caiman Sure, but what about with more complex states, such as rich content from an editor?
what do you need to pass to the server from the editor?
@Ray what do you need to pass to the server from the editor?
Broad-snouted CaimanOP
So post/page.tsx would have all information to push the data to the database.
It needs to get the title from title.tsx, and the content of the editor from editor.tsx, whcih are both client components.
It needs to get the title from title.tsx, and the content of the editor from editor.tsx, whcih are both client components.
you want to insert the data to database from editor.tsx?
Broad-snouted CaimanOP
Yes.
post/page.tsx would use an action to PUSH to the database, and it would use the data from title.tsx and editor.tsx
post/page.tsx would use an action to PUSH to the database, and it would use the data from title.tsx and editor.tsx
what is the title.tsx? why does it have the
title but post/page.tsx doesnt?I think you could use server action in
editor.tsx to insert the dataAnswer
Broad-snouted CaimanOP
I thought server actions can only be called in server components, no?
Broad-snouted CaimanOP
I see, so you suggest passing the title from title.tsx to the editor.tsx as props, and then using the action from there
you just can't define the action in client component directly
@Broad-snouted Caiman I see, so you suggest passing the title from title.tsx to the editor.tsx as props, and then using the action from there
yes because there is no way to pass state from client to server
Broad-snouted CaimanOP
Would that be considered best practice? Or a workaround?
@Broad-snouted Caiman Would that be considered best practice? Or a workaround?
passing data down to client component from server component?
@Broad-snouted Caiman This way ^
yes, server action is the recommended way
Broad-snouted CaimanOP
Alright, thanks!
Broad-snouted CaimanOP
Yup saw, will use it ðŸ‘