React Router (v6) useNavigate TypeScript error: "TS2345: Argument of type 'number' is not assignable to parameter of type 'To'"

Viewed 41

I want to use navigate() to go back in history, but TypeScript shows me an error: TS2345: Argument of type 'number' is not assignable to parameter of type 'To'.

How can I fix this issue?

const navigate = useNavigate()

useEffect(() => {
  setIsLoading(true);
  dispatch(fetchUser(userId!))
    .unwrap()
    .then(({ data }: { data: User }) => {
      setIsLoading(false);
      setUser(data);
    })
    .catch(() => navigate(-1, { replace: true }));
}, []);
1 Answers

Take a look at the useNavigate type declaration:

declare function useNavigate(): NavigateFunction;

interface NavigateFunction {
  (
    to: To,
    options?: { replace?: boolean; state?: any }
  ): void;
  (delta: number): void;
}

The interface expects either To and options arguments or a single delta argument.

By passing two args the types on the first arg no longer match and -1 isn't assignable to the To prop.

Delta navigations only navigate forward/backward through the history stack, so it doesn't make sense to tray and make it a redirect. Remove the second arg.

const navigate = useNavigate();

useEffect(() => {
  setIsLoading(true);
  dispatch(fetchUser(userId!))
    .unwrap()
    .then(({ data }: { data: User }) => {
      setIsLoading(false);
      setUser(data);
    })
    .catch(() => navigate(-1)); // <-- only delta value
}, []);
Related