Server Actions small help
Answered
In&Out posted this in #help-forum
In&OutOP
Why can't i do this?
"use client";
import Link from "next/link";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { createClient } from "../supabase/server";
import { useState } from "react";
export default function Login() {
let [awaitingOTP, setAwaitingOTP] = useState(false);
const [data, setData] = useState("");
const signIn = async (formData: FormData) => {
"use server";
const email = formData.get("email") as string;
const supabase = createClient();
const { error } = await supabase.auth.signInWithOtp({
email,
});
if (error) {
return redirect("/login?message=Could not authenticate user");
}
awaitingOTP = true;
};Answered by Robinhood
You should define the action in a separate file with 'use server'; at the top. As for why you can't do it this way, I think it's because it's bad practice to have server logic on the client
15 Replies
In&OutOP
× It is not allowed to define inline "use server" annotated Server Actions in Client Components.
│ To use Server Actions in a Client Component, you can either export them from a separate file with "use server" at the top, or pass them down through props from a Server Component.I get this error
You should define the action in a separate file with 'use server'; at the top. As for why you can't do it this way, I think it's because it's bad practice to have server logic on the client
Answer
@In&Out Then what's the point of server actions?
It's more intuitive than using API routes and gives you type safety
@Robinhood It's more intuitive than using API routes and gives you type safety
In&OutOP
Yeah but like, can I make that code about functional?
American Crow
you can have it in the same file, just not an inline function
()=> rewrite it toasync function signIn() {
'use server'
...American Crow
this is working for me
export default function Page() {
async function createInvoice(formData: FormData) {
"use server"
const rawFormData = {
customerId: formData.get("customerId"),
amount: formData.get("amount"),
status: formData.get("status"),
}
console.log("🚀 ~ rawFormData:", rawFormData)
// mutate data
// revalidate cache
}
return (
<form className="flex flex-col text-black" action={createInvoice}>
<input name="customerId" />
<input name="amount" />
<input name="status" />
<button type="submit">Submit</button>
</form>
)
}I am stupid i never marked as client component
@American Crow I am stupid i never marked as client component
In&OutOP
so it doesnt work? lol
American Crow
Yea it doesn't i never noticed.
Separate file indeed works
Separate file indeed works
In&OutOP
okay... thank you
closing now