Does react native supports .error() function? - react-native

Im trying to handle a "Network request failed" error (I already allowed unsecured connections from Xcode), But when i try to do something inside the .error() function it crashes and says: .error is not a function; The fetch() works already.
here's an example of it, Im trying to run this code after a fetch function.
fetch('URL',{
'method': 'POST',
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
'body': data}
)
.then((response) => response.json())
.then((responseJson) => {
//Do something
})
.error((error)=>{
console.error(error);
Actions.login()
});

React's fetch method returns a Promise, which doesnot have .error() method. Instead it has .catch() method to catch all errors when fetch fails.
fetch('URL', {
'method': 'POST',
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
'body': data
})
.then((response) => response.json())
.then((responseJson) => {
//Do something
})
.catch((error) => {
console.error(error);
Actions.login()
});

Related

using data returned from promise in another fetch not working

I have a handleSubmit function that I have added two post requests to.
However, one of the post requests relies on the data returned from the first post request. I've attempted to access this data by setting it to a var but it doesn't seem accessible within the second fetch. Not sure if my syntax is wrong.. any ideas?
I believe this should be working but I'm not sure where I'm going wrong. Thanks!
handleSubmit = () => {
fetch('http://localhost:3000/resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
name: this.state.name,
description: this.state.description,
link: this.state.link,
topic_id: this.state.topic_id
})
})
.then(res => res.json())
.then(data => {
this.props.addResource(data)
var dataId = data.id;
})
return fetch('http://localhost:3000/user_resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
resource_id: dataId,
user_id: this.props.users.id
})
})
.then(res => res.json())
.then(data => {
this.props.addUserResource(data)
})
this.props.navigation.goBack()
}
There's 2 problems:
You return some code and then try to run something else. Your this.props.navigation.goBack() statement will never be reached because the function ends when it reaches the return. That is not your main problem though.
fetch is asynchronous. It means that the function handleSubmit will read the two first statements ("fetch resources" and "return fetch user_resources") and then when each fetch is finished they will run their .then() functions.
This means your dataId will be undefined and you need to wait for the first fetch to complete and to execute the 2nd fetch.
handleSubmit = () => {
fetch('http://localhost:3000/resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
name: this.state.name,
description: this.state.description,
link: this.state.link,
topic_id: this.state.topic_id
})
})
.then(res => res.json())
.then(data => {
this.props.addResource(data)
return fetch('http://localhost:3000/user_resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
resource_id: data.id,
user_id: this.props.users.id
})
})
})
.then(res => res.json())
.then(data => {
this.props.addUserResource(data)
})
this.props.navigation.goBack()
}

React Native: Not able to make post request for formData using axios or fetch

I have been trying to make a post request to send formData using axios / fetch, but every time i make a request it throws "Network Error". I have been trying this for couple of days but couldn't do it.
var file = new File([this.state.selectedFileObj], "ISDD_" + this.state.fileName, { lastModified: new Date().getMilliseconds() })
formdata.append("file", file, this.state.fileName);
formdata.append("folderName", this.state.folderName);
formdata.append("userName", "user#domain.com");
formdata.append("documents", documents);
// 1st approach
RNFetchBlob.fetch('POST', url, {
"Content-Type": 'multipart/form-data',
"enctype": 'multipart/form-data',
"Cache-Control": 'sno-cache',
"Pragma": 'no-cache'
}, formdata)
.then((response) => console.log(`1 ${response.text()}`))
.then((RetrivedData) => {
console.log(`2 ${RetrivedData}`);
})
.catch((err) => {
console.log(`err ${err}`);
})
//2nd approach
axios({
url: url, formdata,
method: 'POST',
headers: {
"Content-Type": 'multipart/form-data',
'enctype': 'multipart/form-data',
'Cache-Control': 'sno-cache',
'Pragma': 'no-cache'
},
data: formdata
})
.then((response) => {
console.log(`1 ${response}`)
})
.catch((error) => {
console.log(error)
})
Need a solution for it,
Thanks,

Mapbox navigation api return 422 unprocessable entity

I'm trying to call the mapbox api to get navigation instructions.
Here's the doc: https://docs.mapbox.com/api/navigation/#using-http-post
And here's my api call:
fetch(`https://api.mapbox.com/directions/v5/mapbox/walking?access_token=${Config.MAPBOX_API_KEY}`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({
coordinates: "2.344003,48.85805;2.34675,48.85727;",
}),
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
Unfortunately I get a 422 unprocessable entity error:
I have tried differente coordinates as well...do you guys know what am I missing?
You're passing your coordinates in as a string, but the API expects a number, which is why you're getting a 422. Try this:
fetch(`https://api.mapbox.com/directions/v5/mapbox/walking?access_token=pk.eyJ1IjoiYmRkYXZpZHNvbiIsImEiOiJjaW41MWU5bTcwY2k1dXdtNG54cnhlczFsIn0._R6SrAak5_qF8l31JvSBIA`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'coordinates=2.344003,48.85805;2.34675,48.85727', // <--- Body changed to pass numbers instead of strings
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})

fetch post always pass null to the parameters

There's a fetch post with "userid" as a parameter. I've tested the url and parameter in native android, it works there but here it doesn't take the parameter. It always sends the null value to "userid" parameter. Am I doing smthing wrong here?
fetch('http://zzz.com/zzz/api/battery/gpswithbattery', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
userid: '404',
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
//return responseJson.message;
this.setState({
data: responseJson.message
})
})
.catch((error) => {
console.error(error);
});
I see no mistake you are doing here, and start using es7 syntax, as that'll be even cleaner and easy to find mistakes,
pro-tip: use prettier that'll make to look your code better.
const method = async () => {
const reponse = await fetch("http://zzz.com/zzz/api/battery/gpswithbattery", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
userid: "404"
})
});
const responseJson = await response.json();
this.setState({ data: responseJson.message });
};

React Native - Fetch POST request is sending as GET request

I'm having issues when using FETCH.
I am trying to make a POST request using FETCH in react-native.
fetch("http://www.example.co.uk/login", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'test',
password: 'test123',
})
})
.then((response) => response.json())
.then((responseData) => {
console.log(
"POST Response",
"Response Body -> " + JSON.stringify(responseData)
)
})
.done();
}
When I inspect this call using Charles it is recorded as a GET request and the username and password that should be in the body are not there.
Can anyone help with this issue?
I had this issue when the POST request was to an HTTPS (rather than HTTP) server. For some reason, it would somewhere along the way be converted into a GET request.
It turns out what I was doing incorrectly was sending the request to http://myserver.com:80 rather than to https://myserver.com:443. Once I switched it over to the proper prefix and ports, the request would properly send as a POST.
This worked for me:
let data = {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
body: JSON.stringify({
appoid: appo_id
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': cookie.load('csrftoken')
}
}
return fetch('/appointments/get_appos', data)
.then(response => response.json()) // promise
.then(json => dispatch(receiveAppos(json)))
}
Use FormData. Problem is with JSON.stringify. You can directly import, its not third party
import FormData from 'FormData';
...
var data = new FormData();
data.append("username", "ABCD");
data.append("password", "1234");
fetch('YOUR_URL', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body:data,
})
.then((response) => response.json())
.then((responseJson) => {
console.log('response object:',responseJson)
})
.catch((error) => {
console.error(error);
});
I had the same kind of issue. You have to assign the object, not sure why.
let options = {};
options.body = formdata;
options.header = header;
options.method = 'post';
In my case, the redirect was caused by wrongly formed url for the POST request:
http://localhost:90/Worx/drupal/d8/www//jsonapi
double slash before jsonapi
Because of the wrong url, the browser was redirecting the request and changing the method from POST to GET.
I was able to debug it after reading this:
https://serverfault.com/questions/434205/nginx-https-rewrite-turns-post-to-get
If you wanna do POST request using fetch, You can do like that
fetch('url?email=a#gmail.com&password=a#gmail.com', {
method: 'POST'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
// this.setState({
// data: responseJson
// })
})
.catch((error) => {
console.error(error);
});
Redirection of url converts the POST request into GET requests.(Don't know why)
So make sure of adding trailing arrows if any.
like :"http://www.example.co.uk/login/"
I had the same issue. In my case I had an extra / at the end of my route. I removed it and problem solved.
http://google.com/someData/ to http://google.com/someData
I have made some changes and tested it, works fine for me, check below all the changes:
constructor(props) {
super(props);
this.state = { isLoading: true};
this.getRemoteData();
}
getRemoteData = () => {
fetch('http://www.example.co.uk/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'test',
password: 'test123',
})
})
.then((response) => response.json())
.then((responseData) => {
console.log("RESULTS HERE:", responseData)
this.setState({
isLoading: false,
dataSource: responseJson,
}, function(){
});
})
.catch((error) =>{
console.error(error);
})
};
Check your OPTIONS response. It probably has a 302 redirect or similar.
In our case, Django didn't like it if the URL didn't end in a /
Similar to Rishijay's answer, my issue was with JSON.stringify not properly converting the body of POST request.
The way I solved this was using build from the search-params node module to make it work.
My fetch contents had body like this body: build({...})
This worked for me!
const params = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
id: '1',
name: 'user',
age: '26',
}),
};
fetch('https://yourapi/', params)
.then(response => response.json())
.then(data => console.log(data));