DEV Community

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

Collapse
 
christiankozalla profile image
Christian Kozalla

Nice question, I recently though about what would be my favorite browser API, because there are so many of them, and basically you get them for free (if support is available across the major browser vendors..)

For example, I saw an implementation of a custom parser for URL params.. written long time ago. And I thought. May the browser support of URLSearchParams wasn't that great at that time..(?)

But if we're looking for most unterrated browser APIs, the performance API comes to my mind first. Or the FormData interface which I recently used in a side-project. FormData makes it really easy to obtain data from a <form> without dealing with controlled components (in React) or whatever 😄

Collapse
 
agredalex profile image
Alex Ágreda

can you point me to a good article about this: using FormData interface instead of dealing with controlled components, please

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

Collapse
 
phandungtri profile image
Phan Dũng Trí

Yes, when people talk about form in React, they often make every field in the form become controlled component, which is not good for the performance. FormData is the powerful feature that allows working with form easily in an effective way.