How to Use the FormData Object
Learn how to use the FormData object in JavaScript/TypeScript
The JavaScript FormData interface gives us a way to create an object of key-value pairs representing form fields and their values.
It uses the same format a form would use if the encoding type were set to “multipart/form-data"
. This makes it easy to format form data before sending it along with a fetch or XMLHTTPRequest.
What is the FormData object?
In order to fully understand the FormData object, we need to know what it is. The FormData interface is a native browser interface supported in all major browsers.
This interface was created in order to allow developers easier access to the content of form fields and their values. This helps prepare the content for submission to an API or helps perform validation on said fields.
How to create a FormData Object?
A FormData object can be created with the FormData constructor.
How to access the data in a FormData object?
The FormData object allows us to retrieve values directly through the get() method. You can also append or delete values through the respective methods. You can also set a new value for a key with the set() method.
Finally, you can also loop through the key-value pairs either through looping over the formDate.entries() or by using a for…of loop.
How to create URL query params based on the FormData?
If you want to convert the FormData into a set of query params this is very simple to do. You can pass the FormData object directly into the URLSearchParams.
How to Post FormData With The Fetch API
A FormData object can easily be used with the Fetch API. You can simply pass the object as the body of the request.
How to Use The FormData Event
Whenever a FormData object is created for a form, an event is dispatched against the form. We can listen to this event and bind some logic to it, for example submitting the FormData to an API endpoint.
In the example below we create a FormData object when the form is submitted. We listen to the FormData event and submit the data. This gives us the freedom to act upon the creation of the FormData which might not only be on submit.
Additional Resources
Conclusion
The FormData object is incredibly helpful when dealing with form data, fetch requests, and URL parameter handling. With its browser support being green across the board there’s no reason not to take advantage of this API.
Thanks for reading. If you have thoughts on this, be sure to leave a comment.
And if you want, you can connect with me on LinkedIn or Twitter!
LEAVE A REPLY
Your email address will not be published. Required fields are marked *