how can i import useNavigate in a handler file?

I have a separate file with all my functions but when i try to import my librery react-router-dom and use useNavigate i get errors like

Uncaught TypeError: Cannot read properties of null (reading 'useContext')

or
Uncaught (in promise) Error: Minified React error #321;

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


const navigate = useNavigate();

const onSubmit = async () => {
  navigate('/success');
};

export default {onSubmit};

i tried to declare the variable inside the function but i got error

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

    const onSubmit = async () => {

     const navigate = useNavigate();

      navigate('/success');
    };

>Solution :

You cannot use use hooks outside components. https://reactjs.org/docs/hooks-rules.html

Instead, you can create useOnSubmit hook which you can then use in component body if you want

const useOnSubmit = (cb) => {
   const navigate = useNavigate(); 

   const onSubmit = async () => {
      await cb();
      navigate('/success');
   }
   
   return onSubmit;
}

Now you can use this hook like the following

const SampleComponent = () => {
   const onSubmit = useOnSubmit(() => {
      // do submit logic here
   });

   return <button onClick={onSubmit}>Submit</button>
}

Leave a Reply