Home > Back-end >  Property 'push' does not exist on type 'NavigateFunction' Typescript
Property 'push' does not exist on type 'NavigateFunction' Typescript

Time:04-19

As new Version 6 doesn't allow useHistory; I used "useNavigate" instead of useHistory. After taking user input, those input data is supposed to go next page. While using "History.push" command to pass the data it's showing this error:

Property 'push' does not exist on type 'NavigateFunction'

Here is the code:

import { useNavigate } from "react-router-dom";

export interface UserData {
  name: string;
  gender: string;
  lang: string;
}
const history = useNavigate();
const [UserData, setUserData] = useState<UserData>({
    name: "",
    gender: "Male",
    lang: "React",
  });

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;

    setUserData({ ...UserData, [name]: value });
  };

  const handleSubmit = () => {
    history.push("/exam", UserData);
  };

what am I supposed to change and add?

CodePudding user response:

The useNavigate hook returns a function, not a history object with a push method.

useNavigate

declare function useNavigate(): NavigateFunction;

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

Rename history to navigate so there's no future confusion.

const navigate = useNavigate();

Invoke the navigate function and pass the state in the second argument, the optional options parameter, under the state property.

const handleSubmit = () => {
  navigate("/exam", { state: UserData });
};
  • Related