Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use FormData in react-native?

Hi just learn to use js and react-native. I cant use FormData it always shows unsupported bodyinit type. I want to send text rather then JSON.stringify. Can anyone help me? Thanks!

var data = new FormData() data.append('haha', 'input')  fetch('http://www.mywebsite.com/search.php', {    method: 'post',   body: data }) .then((response) => response.json()) .then((responseData) => {   console.log('Fetch Success==================');   console.log(responseData);    var tempMarker = [];   for (var p in responseData) {    tempMarker.push({     latitude: responseData[p]['lat'],     longitude: responseData[p]['lng']     })   }    this.setState({     marker: tempMarker   });  }) .catch((error) => {   console.warn(error); }) .done(); 
like image 844
phongyewtong Avatar asked Sep 07 '15 15:09

phongyewtong


People also ask

Can I use FormData in react native?

To use FormData in React Native, we can use the FormData constructor. to define the submit function that creates a FormData instance. Then we call append with the key and value to add form data entries.


1 Answers

Here is my simple code FormData with react-native to post request with string and image.

I have used react-native-image-picker to capture/select photo react-native-image-picker

let photo = { uri: source.uri} let formdata = new FormData();  formdata.append("product[name]", 'test') formdata.append("product[price]", 10) formdata.append("product[category_ids][]", 2) formdata.append("product[description]", '12dsadadsa') formdata.append("product[images_attributes[0][file]]", {uri: photo.uri, name: 'image.jpg', type: 'image/jpeg'}) 

NOTE you can change image/jpeg to other content type. You can get content type from image picker response.

fetch('http://192.168.1.101:3000/products',{   method: 'post',   headers: {     'Content-Type': 'multipart/form-data',   },   body: formdata   }).then(response => {     console.log("image uploaded")   }).catch(err => {     console.log(err)   })   }); 
like image 118
bun houth Avatar answered Oct 12 '22 10:10

bun houth