Promise rejection (Network Error) - android

I am using axios to fetch a basic JSON data but keep on getting this error:
Possible unhandled promise rejection (id: 0): Network Error
Now since that error itself was not "as much" useful to know what's going on I changed my code block and used .catch.
Error:
Error: Network Error
at createError (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:82235:11)
at XMLHttpRequest.handleError (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:82107:8)
at XMLHttpRequest.dispatchEvent (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:10284:15)
at XMLHttpRequest.setReadyState (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25988:6)
at XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25836:6)
at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25930:52
at RCTDeviceEventEmitter.emit (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:9523:23)
at MessageQueue.__callFunction (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7339:34)
at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7216:8
at guard (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7155:1)
The code:
componentWillMount() {
axios.get('http://rallycoding.herokuapp.com/api/music_albums')
.then((response) => {
if(!response.ok){
console.log(response.statusText);
}
console.log((response))
}).then((response) => {
console.log("ok")
}).catch((err) => console.log(err))
}
Thanks in advance.

You need to return response inside your first then statement otherwise the chaining will not work.
componentWillMount() {
axios.get('http://rallycoding.herokuapp.com/api/music_albums')
.then((response) => {
if(!response.ok){
console.log(response.statusText);
}
console.log((response))
// return response
return response;
}).then((response) => {
console.log("ok")
}).catch((err) => console.log(err))
}
Hope this helps.

If anyone else faces this problem, I managed to fix it by adding .done(); at the end of the Promise chain.
componentDidMount() {
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then((response) => console.log(response))
.done();
}

Related

React Native android FormData response goes to catch block after .json()

I'm trying to POST data with FormData to get a response, on iOS it works as expected, but on android, it always goes to the catch block, I found out the reason for that is response.json() with error: [SyntaxError: JSON Parse error: Unrecognized token '']
Here is my code:
const onAndroidSucks = () => {
setLoading(true);
let formData = new FormData();
formData.append("number", number.replace(/\s+/g, '').substring(4));
formData.append("id", userID);
formData.append("token", userToken);
fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: formData
}).then(response => response.json()).then(response => {
if (response.res === 'no') {
Alert.alert('ჰეჰე');
} else {
setData(response);
}
setLoading(false);
}).catch(err => { Alert.alert(err.message); setLoading(false); } );
};
I don't understand what the actual problem is here.
It turned out that problem was okHttp on android. Looks like okHttp appends an empty string " " without a known reason.
Here is how I solved that issue with the workaround:
}).then(response => response.text())
.then((res) => JSON.parse(res.trim())).then(response => {

Possible Unhandled Promise Rejection (id: 9): TypeError: Network request failed on React Native

i try to use asyncstorage module to log in into my backend api service. this is the code:
const LoginScreen = (props) => {
const [username,setUsername] = useState('');
const [password,setPassword] = useState('')
const sendCred = async (props)=>{
fetch("http://10.0.2.2:3000/api/user/login",{
method:"POST",
headers: {
'Content-Type': 'application/json'
},
body:JSON.stringify({
"username":username,
"password":password
})
})
.then(res=>res.json())
.then(async (data)=>{
try {
if(data){
await AsyncStorage.setItem('token',data.token)
console.log('data: ' + data.token);
props.navigation.replace("Home");
}else{
alert('Invalid username / password');
}
} catch (e) {
alert('Cannot get TOKEN');
console.log("error",e)
Alert(e)
}
})
}
it work on first try, but i do not know why now i cannot log in with this method with network rejection. can someone tell me whats wrong? thanks!

React native fetch and low connection

I have an issue with a fetch (api call) on react native, when i have a low connection or temporarly lost connection.
My function :
async function getlastcursor(att){
const url=base_url+"/lastcursor;
const formData = new FormData();
formData.append('att', att);
let result="";
try {
result=fetch(url, {
method: 'POST',
headers:{
'content-type':'multipart/form-data'
},
body: formData,
}).then((response) => response.json())
} catch (error) {
}
return result;
}
If log can be help to debug me :
Possible Unhandled Promise Rejection (id: 23):
TypeError: Network request failed
onerror#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:26748:31
dispatchEvent#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:32302:31
setReadyState#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:31386:33
__didCompleteResponse#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:31213:29
emit#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:3316:42
__callFunction#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2648:49
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2361:31
__guard#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2602:15
callFunctionReturnFlushedQueue#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2360:21
callFunctionReturnFlushedQueue#[native code]
I would like to retry automatically when i have a Network request failed (which is when connection is low or temporarly lost).
What can i do to make it ? Use Promise class?
Thanks you

deviceNotReady error : "Registration failed" react-native-twilio-programmable-voice

I am working on react native application and want to integrate the Phone masking feature like Uber do. I have choosen Twilio Phone Masking for this. I have used react-native-twilio-programmable-voice package.
I have integrated this using this link:: https://medium.com/#edzh1/create-a-twilio-voip-calls-in-a-react-native-app-35a729a9613d
I have done server setup successfully, using php. But getting error deviceNotReady error : "Registration failed". I have no idea what I am doing wrong here.
This is initial function I am calling here::
initTwilio = async () => {
const token = await this.getAuthToken();
if (Platform.OS === 'android') {
await this.getMicrophonePermission();
}
const success = await TwilioVoice.initWithToken(token);
if (success.initialized) {
TwilioVoice.addEventListener('deviceReady', () => {
this.setState({ twilioInited: true });
});
TwilioVoice.addEventListener('deviceNotReady', function (data) {
console.log('data', data) // getting error here
});
if (Platform.OS === 'ios') { //required for ios
TwilioVoice.configureCallKit({
appName: 'ReactNativeTwilioExampleApp',
});
}
}
};
getAuthToken = () => {
return fetch('https://myurl/accessToken.php', {
method: 'get',
})
.then(response => response.text())
.catch((error) => console.error(error));
}
Please help, and suggest me what I am doing wrong here.

How to set timeout react-native api call using fetch(GET Call)?

This my code(used to fetch data).
loadApi() {
this.setState({isListLoaded : true})
return fetch('http://www.androidbegin.com/tutorial/jsonparsetutorial.txt')
.then((response) => response.json())
.then((responseJson) => {
this.setState({listView : responseJson.worldpopulation})
this.setState({isListLoaded : false})
ToastAndroid.show('A pikachu appeared nearby !', ToastAndroid.SHORT);
})
.catch((error) => {
console.error(error);
});
}
How can i set a timeout to this specific syntax ?.Please share the code part if you have any.
There is no standard way till now according to this github thread.
However there is one solution, use whatwg-fetch-timeout
sample code :
return fetch('/path', {timeout: 500}).then(function() {
// successful fetch
}).catch(function(error) {
// network request failed / timeout
})

Categories

Resources