Skip to content
Source
Sign inSign up
TanStack/router

Broken type for useServerFn inside useMutation #5352

Send to my agent
OpenChristopher96u(GitHub profile, opens in a new tab) opened this issue 3 comments

Which project does this relate to?

Router

Describe the bug

Hi, I think the type is broken for the useServerFn. I've reproduced and noticed that if I need to use the onSuccess callback I loose the types

Your Example Website or App

https://github.com/Christopher96u/ts-issue-demo

Steps to Reproduce the Bug or Issue

  1. Go to the index/home route

Expected behavior

I expect as user, to have the onSuccess types back or improve the docs if this is the right behaviour

Screenshots or Videos

If I comment out the onSuccess callback there is no TS issues

Image

If I leave the onSuccess callback there is a TS issue

Image

If we use the useServerFn hook at top level (not inside the useMutation hook, we get the types back

Image

Platform

  • Router / Start Version: [e.g. 1.121.0]
  • OS: [e.g. macOS, Windows, Linux]
  • Browser: [e.g. Chrome, Safari, Firefox]
  • Browser Version: [e.g. 91.1]
  • Bundler: [e.g. vite]
  • Bundler Version: [e.g. 7.0.0]

Additional context

No response

  1. The thing is, you can't use useServerFn inside the mutation fn, it violates the rules of hooks. useServerFn is using useCallback under the hood to wrap the function you give it. Hooks can only be used at the top level of the component. So the way you're trying to use is invalid.

    The solution is to do exactly what you did in your last screenshot, put useServerFn at the top-level of the component

  2. The thing is, you can't use useServerFn inside the mutation fn, it violates the rules of hooks. useServerFn is using useCallback under the hood to wrap the function you give it. Hooks can only be used at the top level of the component. So the way you're trying to use is invalid.

    The solution is to do exactly what you did in your last screenshot, put useServerFn at the top-level of the component

    Should be good if we can mention it on the docs

  3. Still, the fact that this works (1) but this doesn't (2), means that there is the possibility to add an overload to useMutation:

    1

    const $createAsset = useServerFn(createAssetFn)
    const createAsset = useMutation({
      mutationFn: $createAsset,
      onSuccess: (data) => {
        // data is correctly typed
      },
    })

    2

    const createAsset = useMutation({
      mutationFn: useServerFn(createAssetFn),
      onSuccess: (data) => {
        // data is UNKNOWN
      },
    })

Sign in to join this conversation.