DEV Community

Discussion on: What are the most underrated browser features and APIs?

Collapse
 
christiankozalla profile image
Christian Kozalla

I've used MDN alot. For example this post
developer.mozilla.org/en-US/docs/W...

One thing I've learnt is to use Object.fromEntries(formData.entries()) to get the values from the form. See the snippet for more details

// html
<form id="myform">
</form>

// js
const formEl = document.getElementById("myform");
formEl.addEventListener("submit", submitFetch);

function submitFetch(event) {
  event.preventDefault();
  const formData = new FormData(this);

  // Obtain values from the named inputs inside the form
  const data = Object.fromEntries(formData.entries());

  try {
    fetch(url, {
     method: "POST",
     headers: {
       "Content-Type": "application/json",
     },
     body: JSON.stringify(data),
   }).then((response) => {})
} catch { /* ... */ }
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
agredalex profile image
Alex Ágreda

thanks

Thread Thread
 
christiankozalla profile image
Christian Kozalla

Oh, and if you are using it in React, you'd likely pass a ref to the FormData constructor - like new FormData(formElRef) instead of getting the element with document.getElementById