TanStackT
TanStack10mo ago
8 replies
spotty-amber

Type Errors when using navigate from useNavigate

Hi, I am getting type errors on my search params when I pass them to the navigate function created by useNavigate. I have put together a very basic example to replicate the issue I am facing:

import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { zodValidator } from "@tanstack/zod-adapter";
import { z } from "zod";
import { Button } from "~/components/ui/button";

const SearchParams = z.object({
  message: z.string().optional()
})

export const Route = createFileRoute('/')({
  component: RouteComponent,
  validateSearch: zodValidator(SearchParams),
  loaderDeps: ({search: {message}}) => ({message}),
  loader: ({deps: {message}}) => {
    return {message}
  }
})

function RouteComponent() {
  const {message} = Route.useLoaderData();
  const navigate = useNavigate()

  const handleClick = () => {
    navigate({to: ".", search: {
      message: "Navigated"
    }})
  }

  return (
    <div>
      <h1>Hello World</h1>
      search: {message ?? "No Search Params"}
      <div>
      <Button onClick={handleClick}>
        Hello
      </Button>
      </div>
    </div>
    
  )
}


The above code produces the following type error:

Object literal may only specify known properties, and 'message' does not exist in type 'ParamsReducerFn<unknown, "SEARCH", string, ".">'.ts(2353)
link.d.ts(118, 5): The expected type comes from property 'search' which is declared here on type 'NavigateOptions<unknown, string, ".", string, "">'


The code works without issue but I don't understand why I am getting the type error from VSCode.
Was this page helpful?