Call server function inside client component nextjs 14
Answered
West African Lion posted this in #help-forum
West African LionOP
I have one client component called signup. I used inside server default page component. Like below...
// Page.tsx
'use server'
import React from 'react'
import SignUpCard from './SignUp-Card'
import useFormSignup from '@/utils/signup'
function SignUpPage() {
const signUp = async (data) =>{
'use server'
console.log({data})
await useFormSignup(data)
return null
}
return (
<SignUpCard signUp={signUp}/>
)
}
export default SignUpPage In above page signup component I have one method called signUp I passed this inside client component like this <SignUpCard signUp={signUp}/> . Now, inside SignUpCard component on button click event I want to call this signUp() method, but it is not called. Here is SignUpCard component // SignUpCard.tsx
function SignUpCard({signUp}) {
const formSubmit = async (data:any) => {
console.log('function call.')
await signUp(data)
};
return(
<form onSubmit={formSubmit}>
<button type='submit'>Submit</button>
</form>
)
}
export default SignUpCard; Now, How Do I solve this? My task is when onSubmit button is called I want to pass data to external API and get back response. ThanksAnswered by Sun bear
if you want to call a server function inside a client component you can just do this:
then just import the server action inside your client component:
// src/actions/auth.ts
// only use "use server" when creating server actions
"use server"
export async function signUp(data) {
// handle sign up
}then just import the server action inside your client component:
// src/components/sign-up-card.tsx
// we declare a "use client" at the top of the file to be able to use "on" events and useState, useEffect and other hooks
"use client"
import {signUp} from "~/actions/auth"
import {useState} from "react"
export function SignUpCard() {
const [data, setData] = useState({
email: "",
password: ""
})
// logic for updating data state
async function handleSubmit() {
await signUp(data)
}
return (
<form onSubmit={handleSubmit}>
{ /* input fields... */ }
<button type="submit">Submit</button>
</form>
)
}17 Replies
Sun bear
There is no need to call "use server" inside top level pages since they are server side by default.
Sun bear
if you want to call a server function inside a client component you can just do this:
then just import the server action inside your client component:
// src/actions/auth.ts
// only use "use server" when creating server actions
"use server"
export async function signUp(data) {
// handle sign up
}then just import the server action inside your client component:
// src/components/sign-up-card.tsx
// we declare a "use client" at the top of the file to be able to use "on" events and useState, useEffect and other hooks
"use client"
import {signUp} from "~/actions/auth"
import {useState} from "react"
export function SignUpCard() {
const [data, setData] = useState({
email: "",
password: ""
})
// logic for updating data state
async function handleSubmit() {
await signUp(data)
}
return (
<form onSubmit={handleSubmit}>
{ /* input fields... */ }
<button type="submit">Submit</button>
</form>
)
}Answer
@Sun bear There is no need to call "use server" inside top level pages since they are server side by default.
West African LionOP
Thanks for the right direction. Now, I want to redirect to other page inside signUp function..
"use server"
export async function signUp(data) {
// ... user creation logic ....
redirect('/dashboard'); // This line gives error.
// handle sign up
} I receive error Error: NEXT_REDIRECT and not redirecting to dashboard.Sun bear
can you share the entire function
also make sure you are importing redirect from
next/navigation"use server"
import { redirect } from 'next/navigation'
export async function signUp(data) {
// ...
redirect("/")
}@Sun bear also make sure you are importing redirect from `next/navigation`
ts
"use server"
import { redirect } from 'next/navigation'
export async function signUp(data) {
// ...
redirect("/")
}
West African LionOP
Yes, Here is full function code..
"use server";
import { redirect } from "next/navigation";
const authSignUp = async (formData: any) => {
console.log("Server-Action", formData);
try {
await fetch("http://localhost:5001/api/workflow/auth/signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(formData),
})
.then(async (response) => {
console.log("response ");
const result = await response.json();
console.log({ result });
redirect("/dashboard");
})
.catch((e) => console.log({ e }));
} catch (error) {
console.log({ error });
}
};
export { authSignUp };Here is folder structure.
Here is error.
Sun bear
don't call redirect inside try {} catch {} block, read more here: https://nextjs.org/docs/app/api-reference/functions/redirect
@Sun bear don't call redirect inside try {} catch {} block, read more here: https://nextjs.org/docs/app/api-reference/functions/redirect
West African LionOP
Yes, right. Thank you so much! There are more rules in nextjs to follow. Can you suggest me any tutorial or video series where I can learn and look more about next.js 14? Thanks again.
Sun bear
I haven't really watched any tutorials, just search up and read what you are interested in implementing. See how other people have done it. Focus on best practices and scaleable code.
Making projects is what will get you good at frontend. Think of an idea, start building a project, fail then do it again until it works.
I have created at least 50 apps that ended after creating the header, now my headers are perfect and the same applies to every part of an application. Cards, layout sections, footers, auth, database and more.
@Sun bear Making projects is what will get you good at frontend. Think of an idea, start building a project, fail then do it again until it works.
West African LionOP
Actually, Currently I am building project in nextjs 14 to learn more about it. I am good at Angular, Reactjs, But not good yet in nextjs. That's why I choose to make one project in nextjs as there are many job opportunity for nextjs rises.
@West African Lion Yes, right. Thank you so much! There are more rules in nextjs to follow. Can you suggest me any tutorial or video series where I can learn and look more about next.js 14? Thanks again.
Double-striped Thick-knee
you can do something like this to redirect from tryCatch block,
"use server"
import { isRedirectError } from "next/dist/client/components/redirect"
import { redirect } from "next/navigation"
export async function serverAction() {
try {
redirect("/")
} catch (error) {
if (isRedirectError(error)) {
redirect("/")
}
}
}Sun bear
or just call redirect after the try/catch block
@Sun bear or just call redirect after the try/catch block
West African LionOP
Thank you both of you! @Double-striped Thick-knee