UNPKG

dpost

Version:

A flexible form handling library for React + VITE using axios.

29 lines (23 loc) 909 B
import React from 'react'; import axios from 'axios'; const dpost = (url, customHeaders = {}) => (formJSX) => { const handleSubmit = async (e) => { e.preventDefault(); const formData = new FormData(e.target); const data = Object.fromEntries(formData.entries()); const hasFileInputs = Array.from(e.target.elements).some((input) => input.type === 'file'); try { const response = await axios.post(url, hasFileInputs ? formData : data, { headers: { 'Content-Type': hasFileInputs ? 'multipart/form-data' : 'application/json', ...customHeaders, }, }); console.log('Post -> data submitted successfully:', response.data); } catch (error) { console.error('Post -> Error submitting form:', error); } }; return React.cloneElement(formJSX, { onSubmit: handleSubmit }); }; export default dpost;