FormData boolean field?

Viewed 11682

I need to use booleans within form data. For example:

let example = new FormData();
example.append('aBoolean', true);

This throws and error as the above 'true' needs to be in string form. Do you know a way I can use booleans within FormData? Alternatively even a way to cast it as a boolean when I get the value by:

example.get("aBoolean")

Assuming i did store the true as a string in the above example.

3 Answers

A simpler solution to me was to convert the data to JSON and assign it to one field in the formData:

Front-end

const formData = new FormData();
formData.append('data', JSON.stringify({ myBool: false, myNumber: 8 }));

Back-end (nodeJs)

const parsedData = JSON.parse(req.body.data);
console.log(typeof parsedData.myBool === 'boolean'); // => true
console.log(typeof parsedData.myNumber === 'number'); // => true

This obviously works with booleans, null and numbers types

I believe the second argument of append or set require a string or Blob, not a boolean.

Wherever youre using this I would just use a getter and setter to convert the formData result to boolean. ie:

get aBoolean() {
    return this.formDataExample.get('aBoolean') === 'true' ? true : false; 
}

set aBoolean(val: boolean) {
   valAsString = val ? 'true' : 'false';
   this.formDataExample.set('aBoolean', valAsString); 
}

Then access aBoolean like it were a normal variable

console.log(this.aBoolean);
this.aBoolean = false; // This goes through the setter

Using an enum would be better than just 'true' or 'false'

Related