在Next.js中的服务器操作

huangapple go评论86阅读模式
英文:

Server Actions in next.js

问题

I am using server actions in next.js as per the documentation [Server Action] https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions
My action code is

"use server"
export async function registerAndLoginUser(data: any) {
 
    console.log(JSON.stringify(data));
}

And the action is used in a client side component

<form
      action={async (data: any) => {
        try {
          await registerAndLoginUser(data);
        } catch (e: unknown) {
          console.error(e);
        }
      }}
    >;

I get an error:

Type '(data: any) => Promise<void>' is not assignable to type 'string'.ts(2322)
index.d.ts(2143, 9): The expected type comes from property 'action' which is declared here on type 'DetailedHTMLProps<FormHTMLAttributes<HTMLFormElement>, HTMLFormElement>'.

In short, the action property only accepts a string value.

英文:

I am using server actions in next.js as per the documentation [Server Action] <https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions>
My action code is

&quot;use server&quot;
export async function registerAndLoginUser(data: any) {
 
    console.log(JSON.stringify(data));
}

And the action is used in a client side component

&lt;form
      action={async (data: any) =&gt; {
        try {
          await registerAndLoginUser(data);
        } catch (e: unknown) {
          console.error(e);
        }
      }}
    &gt;

i get error

Type &#39;(data: any) =&gt; Promise&lt;void&gt;&#39; is not assignable to type &#39;string&#39;.ts(2322)
index.d.ts(2143, 9): The expected type comes from property &#39;action&#39; which is declared here on type &#39;DetailedHTMLProps&lt;FormHTMLAttributes&lt;HTMLFormElement&gt;, HTMLFormElement&gt;&#39;

In short action property only accepts string value.

答案1

得分: 2

你可以通过将你的 @types/react 包升级到最新版本来解决这个 TypeScript 错误。在 @types/react@18.0.38 版本中添加了对异步表单操作的实验性支持。

英文:

You can fix this TypeScript error by upgrading your @types/react package to the latest version. Experimental support for async form actions was added in @types/react@18.0.38

huangapple
  • 本文由 发表于 2023年6月26日 18:05:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76555644.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定