I am pretty new to next.js. I know how to use server actions to submit forms through action. I used to do this in the App
directory based routing system but for a project I have to work on Pages
Directory based routing. now I am facing some issues doing that. Is it even possible to implement that server action form submitting using this structure? if yes then how?
I used this code inside Pages/old/index.tsx
// Pages/old/index.tsx
const Page = () => {
async function handleSubmit(data: FormData) {
"use server";
console.log(data.get("name"));
}
return (
<form action={handleSubmit}>
<input type="text" name="name" />
<input type="number" name="age" />
<button type="submit">submit</button>
</form>
);
};
export default Page;
and It's generating error :
./pages/old/index.tsx
Error:
x "use server" functions are not allowed in client components. You can import them from a "use server" file instead.
,-[C:\Users\tyson\Desktop\demo\pages\old\index.tsx:1:1]
1 | const Page = () => {
2 | ,-> async function handleSubmit(data: FormData) {
3 | | "use server";
4 | |
5 | | console.log(data.get("name"));
6 | `-> }
7 |
8 | return (
8 | <form action={handleSubmit}>
`----
Same code works properly for App Dir based routing but not here. Thank You in Advanced.
Server actions is an experimental feature available only in the app router, so it’s not expected to work under the pages directory.