Form reload problem with Server Actions
Unanswered
discodian posted this in #help-forum
Hi
When I create a simple form in JSX and add an action to it with the
page.tsx
postLogin.tsx
When I create a simple form in JSX and add an action to it with the
action attribute and submit it, the whole page reloads when the server action executes. I understand in HTML we can use event.preventDefault() but with actions, we cannot because execution is done in the server. How do i submit this form without reloading the whole page? I am fairly new to Next, any help is appreciated.page.tsx
"use client";
import { postLogin } from "@/actions/auth/postLogin";
export default function Login(){
return<>
<div className="mt-4">
<h1 className="text-2xl">Login to visioncast</h1>
<form action={postLogin}>
<input className="border" type="email" defaultValue={"admin@admin.com"} name="email" />
<input className="border" type="text" defaultValue={"password"} name="password" />
<button className="border">Login</button>
</form>
</div>
</>
}postLogin.tsx
"use server";
import { BaseURL } from "@/config/constants";
export const postLogin = async (formData: FormData) => {
let email = formData.get("email")?.toString();
let password = formData.get("password")?.toString();
if (!email || !password) return;
const loginResponse = await fetch(`${BaseURL}/login`, {
method: "POST",
body: JSON.stringify({ email, password }),
headers: { "Content-Type": "application/json" }
});
console.log(loginResponse.json());
}