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
})
Related
I am using expo-payments-stripe API for the payment of an android app. And Stripe payment API is getting called from the following firebase function:
exports.payWithStripe = functions.https.onRequest((request, response) => {
stripe.charges.create({
amount: request.body.amount,
currency: request.body.currency,
source: request.body.token,
}).then((charge) => {
response.send(charge);
})
.catch(err =>{
console.log(err);
});
});
Here is the code for the client-side that calls the firebase functions:
payment = async () => {
if (this.state.token) {
fetch(
"https://us-central1-<>.cloudfunctions.net/payWithStripe",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
amount: this.state.amount,
currency: "usd",
token: this.state.token.tokenId,
}),
}
)
.then((response) => response.json())
.then((responseJson) => {
if (
responseJson.status === "succeeded" &&
responseJson.paid == true
) {
this.setState({ status: "succeeded", loading: false });
}
console.log(responseJson);
})
.catch((error) => {
this.setState({ status: "failed", loading: false });
console.error(error);
});
}
};
doPayment = async () => {
const params = {
number: this.state.number,
expMonth: parseInt(this.state.expMonth),
expYear: parseInt(this.state.expYear),
cvc: this.state.cvc,
};
const token = await Stripe.createTokenWithCardAsync(params);
this.setState({ token: token, loading: true });
setTimeout(() => {
this.payment();
}, 5000);
console.log(token);
};
Everything works fine in the test mode. But after deploying the app to the Play store Firebase function is not triggered. Any suggestions on why this might be happening? Also without ejecting expo what other options do I have to make payments from expo react native app for android?
Can you check adding await to the fetch or removing async from the payment function? Also why did you add setTimeout to the payment function call?
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.
I have followed this document https://rnfirebase.io/docs/v4.1.x/links/android and able to run adb shell am start -W -a android.intent.action.VIEW -d "https://abc123.app.goo.gl" com.myapp.superapp to start the app.
How can open a dynamic link https://abc123.app.goo.gl it open the VideoScreen and pass the contentparam
Video:{
screen : VideoScreen,
path:'wvc/:contentparam',
}
So I tried this when clicking https://abc123.app.goo.gl (dynamic link):
componentDidMount () {
Linking.getInitialURL().then((url) => {
console.log('Initial url is: ' + url);
}).catch(err => console.error('An error occurred', err));
}
However app opened but console.log given null
For some reason firebase.links().onLink((url) does not work in RNFB v6.
Here is a comment on this bug from one of RNFB maintainers
https://github.com/invertase/react-native-firebase/issues/3008
Use should use react native Link instead, as a temporary workaround:
https://facebook.github.io/react-native/docs/0.47/linking
Here is an example you can use:
useEffect(() => {
Linking.getInitialURL()
.then(url => {
if (url) {
console.log('Initial url is: ' + group);
}
})
.catch(err => console.error('An error occurred', err));
}, []);
You have to listen to firebase links
componentDidMount() {
const unsubscribe = firebase.links().onLink((url) => {
console.log('dynamic links', url)
// do navigate with url above
// you have to handle your self
});
}
componentWillUnmount() {
unsubscribe()
}
docs: https://rnfirebase.io/docs/v5.x.x/links/reference/links#onLink
Hello I tried to set the state on fetch call like this:
getCats() {
fetch(GLOBALS.API + '/specials.php?action=getCats&key=' + GLOBALS.KEY)
.then((response) => response.json())
.then((responseJson) => {
this.setState = ({
dataSource: "test"
});
Alert.alert("test");
})
.catch((error) => {
console.log(error.toString());
});
}
componentDidMount() {
this.getCats();
console.log(this.state.dataSource);
}
but the line:
console.log(this.state.dataSource);
return me undefined
and I get an alert of "test"
what the problem?
tnx a lot
You Can Make Use of callbacks.
Below is the code example
getCats(successCallBack, failureCallback) {
fetch(GLOBALS.API + '/specials.php?action=getCats&key=' + GLOBALS.KEY)
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
failureCallback();
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data)
successCallBack(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
failureCallback();
});
}
Below is the code for success and failure call backs
successCallBack(data) {
console.log(data)
}
failureCallback() {
alert("failure");
}
Below is the code to bind success and failure callbacks.
getCats(this.successCallBack.bind(this), this.failureCallback.bind(this));
Fetch is asynchronous so it will return immediately, before the code in the then clauses are run. Therefore, setState will not have run before the console logging.
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();
}