Add data to Sveltekit formData

476 Views Asked by At

So I would like to add my specific data to a formData in a Sveltekit Form.

I want to do that because some of my forms inputs are removed from the dom with {#if } so they don't appear in the formData anymore.

Here is my form component:

<form
  action="?/newReservation"
  method="POST"
  use:enhance={({ formData }) => {
    formData = manageFormData();
    console.log(formData.get('numero_chambre'))

    return async ({ result, update }) => {
      console.log(result, update);
    };
  }}
>
...
</form>

And here is my manageFormData() function :

const manageFormData = (): FormData => {
    let data = new FormData();

    let datesArr = dates;
    let debut = datesArr[0];
    let fin = datesArr[1];

    //user infos
    data.append("nom", nom);
    data.append("prenom", prenom);
    data.append("email", email);

    //reservation infos
    data.append("debut", debut);
    data.append("fin", fin);
    data.append("numero_chambre", JSON.stringify(bedroomsChoosen));
    data.append("total", total.toString());
    data.append("nb_petit_dejeuner", nombrePetitDejeuner.toString());
    data.append("jours_petit_dejeuner", JSON.stringify(joursPetitDejeuner));
    data.append("heure_petit_dejeuner", heurePetitDejeuner);

    console.log(data.get('numero_chambre'))

    return data;
  };

In all my console.log() I get the right value for numero_chambre but in my +page.server.ts in the actions whenever I get the numero_chambre data value it returns null, the only data that I get through the formData is the part of the form that is visible on the screen.

So I would like to modify / create the formData to have the values that I want

1

There are 1 best solutions below

1
On BEST ANSWER

There are two issues here, you are reassigning a local variable which has no effect on the object that you destructured it from. I.e. this is like:

let prop = thing.prop;
prop = someOtherThing;

// thing.prop is still the same

Also, even if this is fixed by reassigning the property on the original object, this will not work because SvelteKit does not allow it. You have to modify the original instance of formData.

So either pass the original object into your function and just modify that, or transfer all the data over from the new instance to the original.