Roa
Roa

Reputation: 437

React native post nested form data

I am trying to post nested value with formdata.I tried it like this:

const {phone} = this.state

      let formdata1 = new FormData();
      let formdata2 = new FormData();
      let formdata3 = new FormData();

      formdata1.append("0","h23")
      formdata2.append("address1",formdata1)
      formdata2.append("use_for_shipping",true)
      formdata2.append("first_name","isa")
      formdata2.append("last_name","annamyradow")
      formdata2.append("email","[email protected]")
      formdata2.append("city","ashgabat")
      formdata2.append("state","TKM")
      formdata2.append("postcode","110092")
      formdata2.append("country","TKM")
      formdata2.append("phone",{phone})

      formdata3.append("billing", formdata2)

      console.warn(JSON.stringify(formdata2))

       fetch(`http://arzan.com.tm/market/api/checkout/save-address`, {
          method: 'POST',
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
          },
          body: formdata2



      })

          .then((response) => response.json())
          .then((res) => {
            console.warn('zakaz:   '+JSON.stringify(res))
          })
          }

I have never encountered with this object structure in react-native.I tried it according to my inference about formdata.I know there is some lack.Actual posted data structure should be like this:

{
    "billing" :  {
        "address1" : { "0" : "h23" },
        "use_for_shipping" : "true",
        "first_name" : "john",
        "last_name" : "doe",
        "email" : "[email protected]",
        "city" : "noida",
        "state"  :"DL",
        "postcode" : "110092",
        "country" : "IN",
        "phone" : "8802097347"
    },
    "shipping" : {
        "address1" : {
        "0" : ""
        }
    }
}

It gives Unhadled Promise Rejection.Could anyone possibly help me please?

Upvotes: 3

Views: 414

Answers (1)

Guruparan Giritharan
Guruparan Giritharan

Reputation: 16334

You are using the wrong content type to send formdata, The content type should be 'multipart/form-data' for formdata not 'application/json'. Also consider sending the data as json.

Upvotes: 1

Related Questions