I am very new to Next.js. I have created login page and I want to call API on submit button click. There are few issues which i am getting
- Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with “use server”. Or maybe you meant to call this function rather than return it
- When i press the button, the url which i see on network tab is “localhost” and not what i am passing.
I am already adding "use server"
in the action.ts still getting first error
Login Page:
import Image from "next/image";
import React from "react";
import lady from "../../../public/landing-girl.svg";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import { signInUser } from "../actions/action";
export default function Login() {
const callAPI = async (params: FormData) => {
console.log(params);
await signInUser("[email protected]", "Qwerty1@");
};
return (
<div className="flex flex-1 flex-col justify-center items-center">
<Image
src={lady}
alt="lady"
fill={true}
placeholder="empty"
priority={false}
style={{ objectFit: "cover" }}
></Image>
<div className="w-screen h-screen bg-black/20 z-10" />
<div className="w-fit min-w-[500px] h-auto bg-[#F2F2F2]/95 z-20 absolute rounded-lg items-center flex flex-1 px-10 py-5 flex-col">
<span className="text-primary text-3xl font-semibold">Login</span>
<span className="text-text-primary mt-3">
Welcome back! Please enter your details.
</span>
<form action={callAPI} className="mt-5 w-full">
<Input label="Email Id" placeholder="Enter your email"></Input>
<Input label="Password" placeholder="Enter your passoword"></Input>
<Button className="w-full" type="submit">
Sign In
</Button>
</form>
<span className="mt-5 text-text-primary text-sm">
{"Don't have account? "}
<Link href={"/signup"}>
<span className="text-primary font-semibold">Sign Up</span>
</Link>
</span>
</div>
</div>
);
}
action.ts
"use server";
import { callSignInUser } from "@/lib/server";
export async function signInUser(email: string, password: string) {
const res = await callSignInUser(email, password);
return res;
}
index.ts
export const API_BASE_URL = "http://xxxxxx/api/";
export const createAPIEndpoint = (path: string) => {
return `${API_BASE_URL}${path}`;
};
server.ts
import { isOKResponse, returnError, returnSuccess } from "@/types";
import { createAPIEndpoint } from ".";
export const callSignInUser = async (email: string, password: string) => {
const json = {
email: email,
password: password,
};
const response = await fetch(createAPIEndpoint(`/v1/auth/jwt/create/`), {
method: "POST",
body: JSON.stringify(json),
});
try {
const data = await response.json();
if (isOKResponse(response)) {
return returnSuccess<{}>(data);
}
} catch {
console.log("error");
}
return returnError(new Error("Error fetching newest news"));
};
Network Tab:
Please can someone explain me what is wrong here? Please let me know what shall I change to make it work.