New to javascript/react/node/axios. Not new to programming
Having issues trying to get timeout on axios working in a mobile react app.
I have a node server with API end point set to test; this will accept the request, throw an error and simply not respond.
Eg: throw new Error(“testing for timeout”)
The app is hanging and will not move on until I stop the node server where immediately the catch block is executed.
I can verify that the app made contact with server by having the server do a console.log("hello") before throwing the error
I’ve created a new react app by new folder, “react-native init”, creating a button on app.js to initiate the call. Relevant code:
const axios = require('axios')
const test1Press = async () => {
console.log("test1 pressed")
// obviously not the actual url in this stackoverflow post
axios.defaults.baseURL = 'https://mynodeserver.com/api'
console.log("pre call")
try
{
await axios.post('/debug/throw', {timeout: 2000})
console.log("post call passed")
}
catch (err)
{
console.log("post call failed")
}
}
Console window shows Pre call; then hangs. When I stop node server the app logs immediately with "post call failed"
I have also tried:
axios.defaults.timeout = 2000
and using an axios instance like:
axinst = axios.create({
baseURL: 'https://parcelscan-staging.ctilogistics.com/api',
timeout: 2000
})
console.log("pre call")
try
{
await axinst.post('/debug/throw')
console.log("post call passed")
}
catch (err)
{
console.log("post call failed")
}
I can’t see what I’m doing wrong.
EDIT:
On further research I found forum posts with similar issues; looks like axios timeout may not be reliable as of May 2020; and a year later now in June 2021 ?
Suggested solutions are canceltokens eg:
const source = CancelToken.source();
try {
let response = null;
setTimeout(() => {
if (response === null) {
source.cancel();
}
}, 2000);
response = await axios.post('/url',null,
{cancelToken: source.token});
// success
} catch (error) {
// fail
}
Tested this and working