How to send a message to multiple recipients in react native - react-native

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));
}

Related

promise returned from getRestaurantsFromYelp is ignored

Morning/Evening everybody
So I'm tryna get restaurants from yelpApi(react native App), but the fetch is not working.
First I'm getting a message as what "businesses" isn't a resolved variable, and the response from my getRestaurantsFromYelp() function is getting ignored, don't know why. If anybody could hep me fix that.
const [restaurantsData, setRestaurantsData] = useState(localRestaurants);
const getRestaurantsFromYelp = () => {
const yelpUrl = "api.yelp.com/v3/businesses/search?term=restaurants&location=US"
const apiOptions = {
headers : {
Authorization : `Bearer ${YELP_API_KEY}`,
}
}
return fetch(yelpUrl, apiOptions).then((res) => res.json()).then((json) => setRestaurantsData(json.businesses)); //message => unresolved variable businesses
};
useEffect(() =>{
getRestaurantsFromYelp(); // message => promise returned from getRestaurantsFromYelp is ignored
}, [])

What is this error that I'm capturing here, why does it show line, columns, for React Native app?

The code inside api.login(), when there is a and error like a network error, I get the following at the top layer, is this the right way to capture that? I'm beginning react native development, so unsure if there is anything else I should be improving, any help is appreciated, thank you!!
loggedIn = await api.ping();
const state = store.getState();
if (!loggedIn) {
try {
await api.login(state.User.email, state.User.password);
} catch (error) {
console.log('GOT AN ERROR' + JSON.stringify(error));
}
}
If there is no network connection it returns the following...:
GOT AN ERROR{"line":139075,"column":38,"sourceURL":"http://127.0.0.1:19001/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&minify=false&hot=false"}
The line inside api.login is a catch(error) as well that returns the following:
const login = (email: string, password: string): Promise<Object> =>
axios
.post('/sign_in', { email, password })
.then(res => { ... })
.catch(error) {
return Promise.reject(new Error(error));
}
}
Am I doing this right? Why is that error just a hash with a line, column, etc?

React Native Linking Promise resolved reject not getting called

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));

How to check internet connection every http request in react native and display alert message?

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()

React Native - How to see what's stored in AsyncStorage?

I save some items to AsyncStorage in React Native and I am using chrome debugger and iOS simulator.
Without react native, using regular web development localStorage, I was able to see the stored localStorage items under Chrome Debugger > Resources > Local Storage
Any idea how can I view the React Native AsyncStorage stored items?
React Native Debugger has this built in.
Just call showAsyncStorageContentInDev() in the RND console and you'll be able to see a dump of your app's storage.
You can use reactotron i think it has Async Storage explorer ;)
https://github.com/infinitered/reactotron
Following should work,
AsyncStorage.getAllKeys((err, keys) => {
AsyncStorage.multiGet(keys, (error, stores) => {
stores.map((result, i, store) => {
console.log({ [store[i][0]]: store[i][1] });
return true;
});
});
});
I have created a helper method to log all Storage in a single object (more clean to log for example in Reactotron):
import AsyncStorage from '#react-native-community/async-storage';
export function logCurrentStorage() {
AsyncStorage.getAllKeys().then((keyArray) => {
AsyncStorage.multiGet(keyArray).then((keyValArray) => {
let myStorage: any = {};
for (let keyVal of keyValArray) {
myStorage[keyVal[0]] = keyVal[1]
}
console.log('CURRENT STORAGE: ', myStorage);
})
});
}
react native debugger
right click on free space
With bluebird you can do this:
const dumpRaw = () => {
return AsyncStorage.getAllKeys().then(keys => {
return Promise.reduce(keys, (result, key) => {
return AsyncStorage.getItem(key).then(value => {
result[key] = value;
return result;
});
}, {});
});
};
dumpRaw().then(data => console.log(data));
Maybe late, but none of these solutions fit for me.
On android, with Android Studio open file explorer then go to data/data/your_package_name
Inside you should have a folder called database and inside a file RKStorage.
This file is a SQLite3 file so get your favorite SQLite explorer and explore. If you want one this one does the job : DB Browser for SQLite
I did not find Reactotron to have any type of pretty printing enabled and it's also brutally latent so I just wrote a simple function using lodash. You could use underscore too.
Assuming you have a static mapping of all your keys...
const keys = {
key1: 'key1',
key2: 'key2'
}
export function printLocalStorage() {
_.forEach(keys, (k, v) => {
localStore.getAllDataForKey(v).then(tree => {
console.log(k) // Logs key above the object
console.log(tree) // Logs a pretty printed JSON object
})
})
}
It's not performant but it solves the problem.
You can Define function to get all keys by using async and await
getAllkeys = () => {
return new Promise( async (resolve, reject) => {
try {
let keys = await AsyncStorage.getAllKeys();
let items = await AsyncStorage.multiGet(keys)
resolve(items)
} catch (error) {
reject(new Error('Error getting items from AsyncStorage: ' + error.message))
}
});
}
somefunc = async () => {
try {
var items = await getAllkeys();
var someItems = items.filter(function (result, i, item) {
// do filtering stuff
return item;
});
// do something with filtered items
} catch (error) {
// do something with your error
}
}
I have a expo snack that shows this and also performs a "load". So it is useful for doing a dump of the contents and storing it to a file and loading it up later.
Here are they parts.
const keys = await AsyncStorage.getAllKeys();
const stores = await AsyncStorage.multiGet(keys);
const data = stores.reduce(
(acc, row) => ({ ...acc, [row[0]]: row[1] }),
{}
);
// data now contains a JSONable Javascript object that contains all the data
This ammends the data in the AsyncStorage from a JSON string.
// sample is a JSON string
const data = JSON.parse(sample);
const keyValuePairs = Object.entries(data)
.map(([key, value]) => [key, value])
.reduce((acc, row) => [...acc, row], []);
await AsyncStorage.multiSet(keyValuePairs);
import AsyncStorage from "#react-native-async-storage/async-storage";
export const printAsyncStorage = () => {
AsyncStorage.getAllKeys((err, keys) => {
AsyncStorage.multiGet(keys, (error, stores) => {
let asyncStorage = {}
stores.map((result, i, store) => {
asyncStorage[store[i][0]] = store[i][1]
});
console.table(asyncStorage)
});
});
};
enter image description here