Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading