TanStack / router

🤖 Fully typesafe Router for React (and friends) w/ built-in caching, 1st class search-param APIs, client-side cache integration and isomorphic rendering.
https://tanstack.com/router
MIT License
8.32k stars 670 forks source link

Getting type error when passing FormData as a param in createServerFn validator, handler or middleware #2832

Closed ricardoraposo closed 1 week ago

ricardoraposo commented 1 week ago

Which project does this relate to?

Router

Describe the bug

Receiving type error when passing FormData as param of a server function, as shown in the "Server Functions" docs page after "Getting Started"

Image

Your Example Website or App

No link

Steps to Reproduce the Bug or Issue

As shown in the docs page, below: https://tanstack.com/router/latest/docs/framework/react/start/server-functions

Create a server function using createServerFn(), call one of the available methods ("validator", "handler", "middleware")

export const handleSubmit = createServerFn({ method: "POST" })
  .validator((data: FormData) => {
    if (!(data instanceof FormData)) {
      throw new Error("Invalid form data")
    }
    const name = data.get("name")
    const age = data.get("age")

    if (!name || !age) {
      throw new Error("Name and age are required")
    }

    return {
      name: name.toString(),
      age: Number(age.toString()),
    }
  })
  .handler(async ({ data: { name, age } }) => {
    return `Hello, ${name}! You are ${age} years old.`
  })

export function Form() {
  return (
    <form
      onSubmit={async (event) => {
        event.preventDefault()
        const formData = new FormData(event.target as HTMLFormElement)
        const response = await handleSubmit({ data: formData })
        console.log(response)
      }}
      className="flex flex-col gap-4 p-4"
    >
      <input name="name" />
      <input name="age" />
      <button
        className="bg-blue-500 text-white px-4 py-2 rounded"
        type="submit"
      >
        Submit
      </button>
    </form>
  )
}

Expected behavior

FormData should not throw an error, as it can be sent in a POST request because it can be parsed when sent as a multipart/form-data request

Screenshots or Videos

Image

Platform

Additional context

No response

ricardoraposo commented 1 week ago

solved on #2848