Optimal way to send arrays over formData for server actions?
Answered
Baird's Sandpiper posted this in #help-forum
Baird's SandpiperOP
JSON.stringify() and JSON.parse() is a funky pattern and does not work well, my parsed value always comes out as a single string in an array
20 Replies
Baird's SandpiperOP
data.append("tags", JSON.stringify(tags));
data.append("areas", JSON.stringify(form.getValues("areas")));
formAction(data);both these values are arrays
@Baird's Sandpiper data.append("tags", JSON.stringify(tags));
data.append("areas", JSON.stringify(form.getValues("areas")));
formAction(data);
just do
then on the server do
it should give you an array of tag
for (const tag of tags) {
data.append("tags", tag)
}then on the server do
formData.getAll("tags")it should give you an array of tag
Baird's SandpiperOP
what about more nested and complex arrays of objects?
that are not serializeable
@Baird's Sandpiper what about more nested and complex arrays of objects?
why do you need to use formData for that?
Baird's SandpiperOP
what else could I use? (besides bind )
just pass the value to server action directly
you shouldn't use formData if you need to create the formData yourself
use formData if you make the form with just html
Answer
Baird's SandpiperOP
makes sense. But don't I lose useFormState functionality if I don't use formData
@Baird's Sandpiper makes sense. But don't I lose useFormState functionality if I don't use formData
the point of
useFormState is providing progressive enhancement for the form without javascriptif you are trying to pass complex arrays of object, I don't think your form is gonna work without javascript
so there is no need for using
useFormState anywayBaird's SandpiperOP
I wanted to be consistent with a pattern but that makes sense
this is the second night youve helped me out , can I get your venmo Ill buy you a pizza or something
@Baird's Sandpiper I wanted to be consistent with a pattern but that makes sense
just use the right tools for the right thing 

Baird's SandpiperOP
ya regarding something similar a few nights ago helping me bind to useFormStatus lol