Skip to content

Instantly share code, notes, and snippets.

@skorotkiewicz
Last active May 31, 2024 15:28
Show Gist options
  • Save skorotkiewicz/2de4b8d914dd7af89a92feca2d3b25fd to your computer and use it in GitHub Desktop.
Save skorotkiewicz/2de4b8d914dd7af89a92feca2d3b25fd to your computer and use it in GitHub Desktop.
useFormSubmit React Hook
import React from 'react';
import useFormSubmit from './useFormSubmit';
const FormComponent = () => {
const { formRef, handleSubmit } = useFormSubmit(
'http://localhost:3000', // Bazowy URL API
'submit', // Ścieżka endpointu API
(data) => { console.log('Success:', data); },
(error) => { console.error('Error:', error); }
);
return (
<form ref={formRef} onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input type="text" id="name" name="name" required />
</div>
<div>
<label htmlFor="email">Email:</label>
<input type="email" id="email" name="email" required />
</div>
<button type="submit">Submit</button>
</form>
);
};
export default FormComponent;
const { Hono } = require('hono');
const app = new Hono();
app.use('*', async (c, next) => {
c.req.body = await c.req.parseBody();
await next();
});
app.post('/submit', (c) => {
const { name, email } = c.req.body;
console.log('Name:', name);
console.log('Email:', email);
return c.text('Data received');
});
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
import { useRef } from 'react';
import { Client } from 'hono/client';
const useFormSubmit = (baseUrl, endpoint, onSuccess, onError) => {
const formRef = useRef(null);
const client = new Client({ baseURL: baseUrl });
const handleSubmit = async (event) => {
event.preventDefault();
if (!formRef.current) {
console.error("Form reference is not set.");
return;
}
const formData = new FormData(formRef.current);
const data = Object.fromEntries(formData.entries());
try {
const response = await client[endpoint].$post({ body: data });
if (onSuccess) {
onSuccess(response);
}
} catch (error) {
if (onError) {
onError(error);
}
}
};
return { formRef, handleSubmit };
};
export default useFormSubmit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment