How to execute custom hook when form is submited?

Viewed 29

I'm learning react hooks and I build a simple hook useFetch, it works fine when I need to make a GET request but how could I use it for a POST request that needs to be executed when a form is submitted? As I understood hooks can be only executed at the top level

const useFetch = (url, options) => {

    const [ result, setResult ] = useState(null);
    const [ error, setError ] = useState(null);

    useEffect(() => {

        const fetchData = async () => {
            try {
                const response = await fetch(url, options);
                const res = await response.json();

                if ( response.ok) setResult(res);

            } catch (e: any) {
                 setError(e);
            }

        };
        fetchData();

    }, []);

    return [ result, error];
};

LoginForm.jsx

function LoginForm() {

  const submitForm = async (e) => {
    e.preventDefault();
    // execute useFetch hook here
  }
}
0 Answers
Related