Hartan Docs
  • 👋Welcome
  • 🗃️Components
    • Accordion
    • Button
    • Card
    • Carousel
    • Dropdown
    • Footer
    • Form
      • SimpleForm
    • Hero
    • Navbar
    • Popup
    • Sidemenu
    • Snippet
    • Statistics
    • Team
    • Testimonial
  • 🪝Hooks
    • useAccordion
    • useCarousel
    • useCopy
    • useDropdown
    • useFetch
    • useForm
    • usePopup
    • useSidebar
  • 🔴Important
  • ✍️CONTRIBUTING.md
Powered by GitBook
On this page
  1. Hooks

useForm

PrevioususeFetchNextusePopup

Last updated 1 year ago

The useForm hook is used inside the component. It uses the hook and is a specialized hook for submitting form data to the provided URL endpoint.

This hook is a public hook and available for the users to use.

Code

import { useState, useEffect } from "react";
import useFetch from "./Fetch";

export default function useForm(actionURL) {

    const [data, setData] = useState({});
    const [, postData] = useFetch();
    const [submitted, setSubmitted] = useState(false);
    let [result, responseStatus] = "";
    const [returnValue, setReturnValue] = useState({});

    const updateData = (e) => {
        setData({
            ...data,
            [e.target.name]: e.target.value
        })
    };

    const submit = async (e) => {
        e.preventDefault();
        [result, responseStatus] = await postData(actionURL, data);
        setSubmitted(true);
        e.target.reset();
        setReturnValue({
            result: result,
            responseStatus: responseStatus
        })
    };

    useEffect(() => {
        setTimeout(() => {
            setSubmitted(false);
        }, 2500);
    }, [submitted]);

    return [updateData, submit, submitted, returnValue];
}

Explanation

  • It accepts a single parameter, a URL endpoint provided to fetch.

  • It returns the following:

    • updateData -> a function to update form fields for controlled form.

    • submit -> a function to submit the form data.

    • submitted -> a state value which tells if the form is submitted or not.

    • returnValue -> a function to return the value responded by the endpoint after submitting the form data.

Usage

// App.jsx
import { Form } from "react-hartan-js"

function App() {

  const [updateData, submit, submitted, returnValue] = useForm("https://jsonplaceholder.typicode.com/posts");

  return (
    <>
      <Form updateData={updateData} submit={submit} submitted={submitted}></Form>
    </>
  )
}

export default App

As you can see above it uses the and hook of the React internally for toggling the state of each accordion label.

🪝
Form
useFetch
useState
useEffect