I am using react native linking component for opening call application.call suggestion dialog get opened but when I click on cancel it does not return me any promise
static makePhoneCall = (mobileNumber) =>
{
let phoneNumber = '';
if (Platform.OS === 'android') {
let userMobile = `tel:${mobileNumber}`
phoneNumber = userMobile;
}
else {
let userMobile = `tel://${mobileNumber}`
phoneNumber = userMobile;
}
Linking.openURL(phoneNumber).then(() => {
alert('success')
}).catch(() => {
alert('failure')
});
return 'default`
}
classname.makePhoneCall(this.state.item.mobileNumber)
I want to know how to handle openUrl Promise with some example, I have share code of what I have done. I am using react native version 0.59.9
You should check to see if theres an app available to handle the url first.
Linking.canOpenURL(phoneNumber)
.then((supported) => {
if (!supported) {
console.log("Can't handle url: " + url);
} else {
return Linking.openURL(url);
}
})
.catch((err) => console.error('An error occurred', err));
Related
I am using react native, and axios.
I have two parts.
The exercice list that is rendered with useEffect in a div. Inside, there is a Input form which once pressed the Add set button, the set is added to the database and the exercices are fetched again with the passed function.
The main problem is that when I first add an exercice, the exercice s not rendering. I must go back and come again in the page to render the first one. after doing this process I can add as many exercices... And with delete is same. I can delete any exercice but when deleting the last one, it persist and I must leave the page to see the changes...
THIS IS THE FUNCTION THAT ADD THE exercices. It executes once the alert button is pressed
const NewExercice = ({dayID, getAllEx}) => {
// States and ontext change functions
const [exName, setexName] = useState('');
const [comment, setcomment] = useState('');
const handleExname = text => setexName(text);
const handleComments = text => setcomment(text);
// Add new exercices
const handleNewExercice = async () => {
try
{
const status = await data.post('/api/create-exercice', {dayID, exName, comments: comment});
Alert.alert(
'Exercice created',
'Please add new sets to existing exercices',
[
{
text: 'Ok!',
// Fetch again for all the exercices
onPress: getAllEx
}
]
)
}
catch (error)
{
console.log(error);
}
}
Bellow is the component that adds map over the array state
<View>
{error ? (<Text>No exercices created yet.</Text>) :
exArray.map(obj => (
<ExerciceWrapper getAllEx={getAllExercices} navigation={navigation} key={obj.exID} object={obj} />
))}
</View>
Bellow is the function that fetch the data from the DB and set the state to be able to be rendered in the component above
const getAllExercices = async () => {
try
{
const response = await data.get('/api/get-all-ex/' + dayID);
setExArray(response.data);
}
catch (error)
{
if (error.response.status === 404) return setError(true);
else return console.log(error);
}
}
useEffect(() => {
getAllExercices();
}, []);
You need to toggle the error value when you have successful fetch as well
update code to this
const getAllExercices = async () => {
try
{
const response = await data.get('/api/get-all-ex/' + dayID);
setExArray(response.data);
setError(response.data.length < 1)
}
catch (error)
{
if (error.response.status === 404) return setError(true);
else return console.log(error);
}
}
hey guys good morning i am having this issue and couldn’t figure out. I am using the new SDK("react-native-purchases": "^4.5.3"), and also EXPO MANAGED FLOW("expo": "~44.0.0"), all updated.
It is always getting in the catch of those functions in the useEffect.
evaluating RNPurchases.isConfigured
This is my code:
useEffect(() => {
const connectRevenueCat = async () => {
Purchases.setDebugLogsEnabled(true)
if (Platform.OS === 'android') {
console.log('entrou 3')
await Purchases.setup('mypass', 'null')
}
}
connectRevenueCat()
const getPackages = async () => {
try {
const offerings = await Purchases.getOfferings()
if (offerings.current !== null) {
setProducts([offerings.current.availablePackages[0].product])
}
} catch (e) {
// put this on screen to version 18
setError(e?.message + 'O meu errinho do bem')
}
}
getPackages()
}, [])
Thanks for any help
I've tried #react-native-community/netinfo to check the internet reachability. But the scenario I want to implement is, suppose if my device is connected to a wifi hotspot from another device and if that device's mobile data is turned off I want to show an offline toast.
componentDidMount() {
NetInfo.addEventListener(status => {
this.props.checkOnlineStatus(
status.isConnected,
status.isInternetReachable
);
this.setState({
isConnected: status.isConnected,
isInternetReachable: status.isInternetReachable
});
});
}
render() {
if (!this.state.isInternetReachable && this.props.isOfflineNoticeVisible) {
return <MiniOfflineSign />;
}
return null;
}
But in this case, when the mobile data of the other device is turned off, it doesn't handle the change.
The non-deprecated way (using functional components) with the #react-native-community/netinfo package is now:
import React, { useEffect } from "react";
import NetInfo from "#react-native-community/netinfo";
useEffect(() => {
return NetInfo.addEventListener(state => {
// use state.isInternetReachable or some other field
// I used a useState hook to store the result for use elsewhere
});
}, []);
This will run the callback whenever the state changes, and unsubscribe when the component unmounts.
These connection types could help: https://github.com/react-native-community/react-native-netinfo#netinfostatetype
Otherwise:
Then to be sure, you are online just implement a fetch with timeout:
export default function(url, options, timeout = 5000) {
return Promise.race([
fetch(url, options),
new Promise((_, reject) => setTimeout(() => reject("timeout"), timeout)),
]);
}
Then use it like this:
fetchWithTimeout(url, options)
.then(resp => {
if (resp.status === 200) {
let json = resp.json().then(j => {
return j;
});
})
.catch(ex => {
// HANDLE offline usage
if (ex === "timeout") return true;
//ANY OTHER CASE RETURN FALSE
return false;
}
async function InternetCheck() {
const connectionInfo = await NetInfo.getConnectionInfo();
if (connectionInfo.type === 'none') {
alert('PLEASE CONNECT TO INTERNET');
} else {
//navigate to page or Call API
}
}
I am implementing an application which sends SMS to multiple recipients from react native app for IOS.
I am using this library
React-native-communication
please answer this question.
Thank you in advance.
Have you checked out the react-native-sms package?
Its SMS.send function supports an options parameter that can handle multiple recipients. https://github.com/tkporter/react-native-sms#using-the-module
Or you can use Linking from 'react-native':
const onPressSendMessage = () => {
let numbers = '';
contacts.forEach((phoneNumber: string) => {
numbers += `${phoneNumber},`;
});
numbers = numbers.slice(0, -1);
const url = (Platform.OS === 'android')
? `sms:${numbers}?body=${text}`
: `sms:/open?addresses=${numbers}&body=${text}`;
Linking.canOpenURL(url).then((supported: boolean) => {
if (!supported) {
console.log('Unsupported url: ', url);
} else {
Linking.openURL(url).then(() => {
navigateBack(); // or something else
});
}
}).catch((err: string) => console.log('An error occurred', err));
}
I'm just trying to check internet connection when app launches and also check internet connectivity before calling HTTP Request.I have seen some example but it's confusing for me.Please guide me.
You can use the NetInfo API from react native.
Here is the example:
componentDidMount() {
NetInfo.isConnected.addEventListener(
'change',
this._handleConnectivityChange
);
NetInfo.isConnected.fetch().done(
(isConnected) => { this.setState({isConnected}); }
);
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener(
'change',
this._handleConnectivityChange
);
}
_handleConnectivityChange = (isConnected) => {
this.setState({
isConnected,
});
};
render() {
return (
<View style={styles.container}>
<Text>{this.state.isConnected ? 'Online' : 'Offline'}</Text>
</View>
);
}
}
Thereby the above code lets you know if you are having internet before making any api call in your app.
You can refer https://facebook.github.io/react-native/docs/netinfo.html for more.
Here is the example:
import { NetInfo,Alert } from 'react-native';
const netStatus = await NetInfo.fetch()
if (netStatus === 'none' || netStatus === 'NONE') {
Alert.alert("Internet not connected ")
return []
}
There probably is a better way to do this, but you could do a console.log() before the HTTP request and pass in parameters of the API, if you get a result of the title in your console, then you're connected to the internet, otherwise you're not.
You should hook this into your api calls before making them. In such case a higher order function would be useful.
import NetInfo from "#react-native-community/netinfo";
import api from "./MyApi"
//higher order function for api calls
const connectionWrapper = async (errorHandler, apiRequest) => () => {
NetInfo.fetch().then(state => {
return state.isConnected
? errorHandler(state)
: apiRequest()
})
}
//use connection wrapper to build your resource calls
const apiCall = connectionWrapper(
state => ...handleError,
api.resource({ myParams : "myParams"})
)
//now you can reuse api call which should return a promise or anything else that you want
var firstCall = apiCall()
var secondCall = apiCall()
var thirdCall = apiCall()