IdoPesok / zsa

https://zsa.vercel.app
MIT License
436 stars 13 forks source link

Unable to use useServerAction on chained procedure #131

Closed teamkuka closed 2 weeks ago

teamkuka commented 2 weeks ago

I am not sure if this is something not doable, thus a request, or something that I am doing wrong. First, I create an server action using a procedure that requires the admin role I end the function with .createServerAction();

export const createProductAction = createServerActionProcedure(adminProcedure)
  .input(createProductSchema)
  .handler(async ({ input }) => {
    try {
      const { error } = await db.from("products").insert([
        {
          name: input.name,
        },
      ]);
    } catch (error) {
      throw new Error("An error as occured");
    }
  })
  .createServerAction();

Then, in my client form CreateProduct, I want to use the useServerAction hook and deconstruct the props to handle the states.

But I have a TS error on createProductAction, in that line: const {isPending,data,execute,isError}=useServerAction(createProductAction) and can't actually use that file.

What am I doing wrong? I am so sorry if this is not the right place for this request.

IdoPesok commented 2 weeks ago

Hi, try this:

export const createProductAction = adminProcedure
  .createServerAction()
  .input(createProductSchema)
  .handler(async ({ input }) => {
    try {
      const { error } = await db.from("products").insert([
        {
          name: input.name,
        },
      ]);
    } catch (error) {
      throw new Error("An error as occured");
    }
  })

The issue in your current code: createProductAction is not a "completed" action. A completed action has createServerAction() followed eventually by a handler.

In the updated code above we create a new server action from the adminProcedure. Then we assign the input schema. Finally, we finish with the handler which completes the action and handler returns the async function. Hopefully that makes sense!

IdoPesok commented 2 weeks ago

Hi, I am going to close this issue for now. If the code I provided does not work, please ping back on here and I will reopen.