Next.js Discord

Discord Forum

How? i have a function which will be used on client component and server side(api/backend)

Answered
Cane di Oropa posted this in #help-forum
Open in Discord
Cane di OropaOP
Currently the function is on server side lib/utils.ts for example.

Now my client component wants to use it, it can't, because we cannot just pass function into component without "with server" tag, right?

I create a server action specifying "use server" which calls this function and pass it as props to client component. Is there any better approach?

utils.ts

export const testFunction = (name:string, age:string) => {
...
}


Page.tsx

import "utils.ts"
import "ClientComponent.tsx"

const testFunctionAction = (formData:FormData) => {
"use server"

const result = testFunction(formData.get("name"), formData.get("age"));

return result
}

<ClientComponent testFunctionAction={testFunctionAction} />


ClientComponent.tsx

export default function ClientComponent({testFunctionAction}:{testFunctionAction:any}) {

// here is where I use testFunctionAction

}



With such set up, my testFunction could be used on server and client side, but is it too tedious or over-engineered?
Answered by Double-striped Thick-knee
if you put "use server" on top of a file, all the exported functions from that file becomes server actions.
View full answer

11 Replies

Cane di OropaOP
there might be syntax error but you got the idea
Cane di OropaOP
wow is it? let me try
@Cane di Oropa wow is it? let me try
Double-striped Thick-knee
//action.ts

"use server"

export async function ServerAction (){
    return "Returning data from server action"
}

//clientComponent.tsx

"use client"
import { ServerAction } from "./action.ts"

export default function ClientComponent() {
    return (
        <div
            onClick={async () => {
                const data = await ServerAction()
                console.log(data)
            }}
        >
            Click
        </div>
    )
}
Double-striped Thick-knee
if you put "use server" on top of a file, all the exported functions from that file becomes server actions.
Answer
Chinese Alligator
I create a server action specifying "use server" which calls this function and pass it as props to client component. Is there any better approach?
Why do you need something "better"? I mean what are the problems with that approach?
@Chinese Alligator > I create a server action specifying "use server" which calls this function and pass it as props to client component. Is there any better approach? Why do you need something "better"? I mean what are the problems with that approach?
Cane di OropaOP
huh? so whats your coding practice, if you feel sth is redundant or could be improve, you dont look for the possible alternative way to do it?
"as long as it works and there are no problems with my current approach"?
since you are not providing any valuable input your reply doesnt contain any value here and yet im not sure why did you reply