๐ŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

FormData and Fetch – Javascript example

Let's take a look at how we can build a form that is submitted via the browser fetch function and packages the data using the FormData API.

While both the fetch() and the FormData API are fairly straightforward wiring them together requires a few extra steps.

By the end of this example, we will build the below form that will make a POST request to the jsonplaceholder.typicode.com endpoint and displays the results.
form preview used in the FormData and Fetchย example

Building the HTML form

The HTML form is pretty straightforward. A couple of labels and input fields:

<form 
    action="https://jsonplaceholder.typicode.com/comments" 
    id="comments-form">
    <label for="user">๐Ÿง‘โ€ Name: </label>
    <input type="text" name="name" value="John Doe"><br/>
    <label for="password">๐Ÿ“ฉ Email:</label>
    <input type="text" name="email" value="john_doe@gmail.com"><br/>
    <label for="comment">๐Ÿ’ฌ Comment:</label>
    <input type="text" name="comment" value="Some comment here"><br/>
  <input type="submit" value="Add comment">
</form>

Please note that the form fields must have a name attribute to be added to the FormData object. If they don't have the name theyโ€™re skipped. The id property doesnโ€™t count.

Given that we don't want to have the default behavior for the summit event of the form we will intercept and cancel it:

const handleFormSubmit = async (e) =>  {
    e.preventDefault()
    // 1. wrap the form in a FormData object
    // 2. send the object via the fetch function
}

const fComments = document.querySelector("#comments-form")
fComments.addEventListener("submit", handleFormSubmit)

Serializing the fields of the form with the FormData API

The next step will be to wrap all of the fields of the form in a FormData object. We can easily do that with Object.fromEntries(), and after that serialize the data:

const formDataToJson = (form) => {
  const formData = new FormData(form)
  const serializedData = Object.fromEntries(formData.entries())
    return JSON.stringify(serializedData)
}

const handleFormSubmit = async (e) =>  {
    e.preventDefault()

    // 1. wrap the form in a FormData object
    const form = e.currentTarget
    const data = formDataToJson(e.currentTarget)

    // 2. send the object via the fetch function
}

Keep in mind that if you are appening arrays in formdata you will need to write your own custom serializing function.

Sending the FormFata with the fetch() function

The final step will be to send the wrapped data with the fetch() function.

For this we will make a dedicated function that will make the request:

const makeRequest = async (url, data) => {
    const options = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            Accept: "application/json",
        },
        body: data,
    }
    const response = await fetch(url, options)
    if (!response.ok) {
        const errorMessage = await response.text()
        throw new Error(errorMessage)
    }
    return response.json();
}

Given that we may get some errors it may be a good idea to wrap it all in a try-cath block:

const handleFormSubmit = async (e) =>  {
    e.preventDefault()

    const form = e.currentTarget
    try {
        const data = formDataToJson(e.currentTarget)
        const res = await makeRequest(form.action, data)
        console.log(res)
    } catch (er) {
        console.error(er)
    }
}

As a side note, we have used the fetch API also in the NextJs 13 GET example.

You can check out here the full codepen example.

When the user will press the submit button she/he will get a console message, confirming the POST action, similar to the one below:

{
    name: 'John Doe', 
    email: 'john_doe@gmail.com', 
    comment: 'Some comment here', 
    id: 501
}

The FormData is also used in the example for uploading multiple files with React.

๐Ÿ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

๐Ÿ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *