useForm
The useForm hook is used inside the Form component. It uses the useFetch 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
Last updated