Inspired by this StackOverflow question.

The issue is that JSON.stringify() does not handle FormData well. However, it can handle arrays. Therefore we can use Array.from() to convert FormData into Array:

Array.from(data) will produce something like this:

Deserialization of the array is pretty easy:

However, there are a few gotchas:

  1. If el.type === 'file', you cannot assign it any value other than '': an attempt to do so will result in a SecurityError exception. Thus, we first need to check the type of the field, and if it is a file, then assign an empty string to it.
  2. If we have elements with the same name — like this:

    then form.elements will store them as RadioNodeList, like this:
  3. FormData skips disabled elements.

Taking the above into account, we can rewrite deserialization like this:

This solution is still not an ideal one: for example, it is possible to break it by giving the same name to inputs of different types (does anyone do that?). However, it can give you a starting point in writing your own code.

Store FormData object in localStorage
Tagged on:     

Leave a Reply

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