I'm learning React Native and I was looking up how to make a promise chain with an API call as referenced here: https://facebook.github.io/react-native/docs/network.html#handling-the-response.
In looking how to get user permissions, I looked at the docs page for it (https://facebook.github.io/react-native/docs/permissionsandroid.html) and wondered if the promise concept could be applied here to make it a little
My main question is this: How does promises improve functionality (if at all) and what is the best way to adapt code to use promises?
Here is some other code that I would use for easy reference:
async requestLocationPermission() {
const chckLocationPermission = PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
if (chckLocationPermission === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You've access for the location");
} else {
try {
const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'This App required Location permission',
'message': 'We required Location permission in order to get device location ' +
'Please grant us.'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You've access for the location");
} else {
console.log("You don't have access for the location");
}
} catch (err) {
console.log(err)
}
}
};
The short answer is yes.
If you need the data from your API request, then you need to use promises.
For more on why you would need to use a promise, you want to learn about more about the call stack.
I think there's a small confusion (which is pretty common), but the code you linked is also using promises.
Async/Await is a new JavaScript feature that makes writing promises easier.
There are a more than a few ways you can write promises in JavaScript e.g. Fetch, Promise, Async/Await. Not to mention libraries like AngularJS have their own implementation of this.
I'd recommend to study up on the Call Stack first and then go from there.
Simply:
You are writing much cleaner code with async await rather than then() catch() etc. methods
If you have other programming language knowledge probably you miss try/catch blocks. It allows you write sync & async methods in same block.
Personal recommendation you should be familiar with callbacks => promises => generators => async await (learn in order). It's actually your decision to use which one best fits for your purposes. I'd suggest to look very detailed guide about these topics (he actually wrote a book for just these topics xd) You Don't Know JS: Async & Performance
Related
I have a 3 part question from important to less important:
Does someone know if there is a package to do phone calls trough the internet as Whatsapp and Facebook do?
Would it even be possible to do it without a phone number?
For example, only knowing someone's device id.
And can you even make your "ring page" custom? So adding functionalities while calling.
Thank you in advance!
Yes this is possible. There are plenty of ways to attack this but I would recommend using a React Native wrapper for Twilio (https://github.com/hoxfon/react-native-twilio-programmable-voice).
import TwilioVoice from 'react-native-twilio-programmable-voice'
// ...
// initialize the Programmable Voice SDK passing an access token obtained from the server.
// Listen to deviceReady and deviceNotReady events to see whether the initialization succeeded.
async function initTelephony() {
try {
const accessToken = await getAccessTokenFromServer()
const success = await TwilioVoice.initWithToken(accessToken)
} catch (err) {
console.err(err)
}
}
// iOS Only
function initTelephonyWithUrl(url) {
TwilioVoice.initWithTokenUrl(url)
try {
TwilioVoice.configureCallKit({
appName: 'TwilioVoiceExample', // Required param
imageName: 'my_image_name_in_bundle', // OPTIONAL
ringtoneSound: 'my_ringtone_sound_filename_in_bundle' // OPTIONAL
})
} catch (err) {
console.err(err)
}
For that approach I believe you have to have a phone number but you can build out the ui however you like.
If you are not into the Twilio approach, you can use pure JS libraries to do the trick such as SipJS.
There are also tutorials on Youtube which can lead you through the process like this.
I recommend you Voximplant, https://voximplant.com/docs/references/articles/quickstart,
it's easy to use and has clear documentation.
Im currently refactoring an app and converting all my base code into vue. One of my requirements is to do server side rendering.
I have been follow vue ssr example along with hacker news example to help me understand ssr.
I do have however a question for which I cant find any good answer, and before further development, I want to make sure we are doing the right thing.
I want to know if its a good practice to have some actions in a vue store calling an api for server side rendering.
All the examples I have found deal with a real external endpoint they connect and perform request. But that is not the setup we have.
We do have a "normal" express app with its own endpoints; so, for example, express router looks a bit like this:
// This is our post model, it lives on the same app, so its not a external API
app.get('/posts', (req, res) => Posts.getPosts());
// Resolve request for SSR rendering, pretty much the same as in [vue ssr example](https://ssr.vuejs.org/guide/routing.html#routing-with-vue-router)
app.get(
const context = { url: req.url }
createApp(context).then(app => {
renderer.renderToString(app, (err, html) => {
if (err) {
if (err.code === 404) {
res.status(404).end('Page not found')
} else {
res.status(500).end('Internal Server Error')
}
} else {
res.end(html)
}
})
})
);
This part works fine on both client and server. If you request something to /posts you get your response back.
To have a more modular code, we are using vuex stores; being one of the actions called fetchPosts and this action is the responsible of fetching the current posts in the view.
...
actions: {
fetchPosts({ commit }) {
return $axios.get('/posts').then((response) => {
commit('setPosts', {
posts: response.data
});
});
}
},
...
I believe for client side this is good, but when rendering on the server, this is probably not optimal.
Reason being axios performing an actual http request, which will also have to implement auth mechanism, and in general, really poor performant.
My question is: is this the recommended and standard way of doing this ?
What are other possibilities that works in server and client ?
Do people actually creates separated apps for api and rendering app ?
Thanks !
I know this is an old question, but for future visitors:
The recommended way is to leverage webpack module aliases to load a server side api for the server and a client side api for the browser. You have to share the same call signature which allows the api to be "swapped".
This of course greatly improves performance as the server side api can do direct db queries instead fetching data over http.
In essence your webpack.server.config.js should have:
resolve: {
alias: {
'create-api': './create-api-server.js'
}
}
In your webpack.client.config.js:
resolve: {
alias: {
'create-api': './create-api-client.js'
}
}
Importing create-api will now load the required api.
Have a look at https://github.com/vuejs/vue-hackernews-2.0 to see a full example.
I am running redux on node. To handle asynchronous actions, like reading a file or listing of a directory, I am using redux-thunk in combination with Promises. So a typical action can look like that:
const
fs = require('fs'),
{ promisify } = require('util'),
readdir = promisify(fs.readdir);
const listFiles = dir => dispatch =>
readdir(dir)
.then(files => dispatch({
type: '…',
payload: { files }
}));
So:
try {
store.dispatch(listFiles('/some/path'));
catch (error) {
//some rescue plan here,
//won't work if directory not exists
}
wont work here, because the action is asynchronous and right now, the only way I see to handle all errors is to add a .catch() to all promises in all actions and dispatch an error action there.
That has two downsides:
a lot of code repetition and
i need to know all possible errors in ahead.
So my question is: Is there any way to create a global error handler, which will also be called if an asynchronous action fails, such that I can add some error indicating information to the state, which can be displayed?
Could that be possible with a »storeEnhancer« or some »middleware«?
UPDATE
I could find something that is really helpful:
process.on('unhandledRejection', (reason, promise) => {
console.log(reason.message);
});
That callback is triggered whenever a Promise is rejected and no catch block is added. Right now that seams to do the trick, but anyway, I would prefer a solution that basically does the exact same thing, but only for rejected Promises which are triggered within store.dispatch(), so only when an error within the processing of actions/middleware/reducers within redux comes to happen.
If you're looking for a redux middleware solution, take a look at redux-catch.
I've built a ReactNative app that uses redux, as well as Wix's react-native-navigation library (HIGHLY recommend btw), and am trying to improve the user experience when network connection is lost - really just a simple alert that lets the user know.
I've got all of my fetch() calls in one api.js lib file, and what I would love to do, is wrap each request with a function that checks for connection before fetching (as opposed to doing some sort of per-component implementation I've seen in other SO suggestions).
I've read a bunch about facebook's NetInfo (https://facebook.github.io/react-native/docs/netinfo.html) API, however there are still open issues on it w/ regards to the simple NetInfo.isConnected.fetch().then((isConnected) => {} use case (it always returns false, per the issues open).
I've tried something like this inside the fetch function:
static get(route, params, header) {
return NetInfo.isConnected.fetch().then((isConnected) => {
if ( isConnected )
{
// Run / return your API call
}
else
{
Alert.alert('No Internet Connection', 'Please connect and retry.',[{text: 'OK'}],{ cancelable: false });
}
});
}
I'm wondering if anyone has either successfully utilized the NetInfo api in this way, or if you've come across a better solution for this (likely) common problem.
I'm new to RxJs and Angular2, and I'm trying to properly handle errors. I've seen some examples with Observables that have onNext, onError and onCompleted events (e.g. here, but all of the Angular2 http examples that I see seem to just use .catch and .map methods, and I'm not sure how that relates to the OnNext/OnError/OnCompleted model. I'm working with the code from here):
let stream = this.http.request(options.url, options)
.catch(error: any) => {
this.errorsSubject.next(error);
return Observable.throw(error);
})
.map(this.unwrapHttpValue)
.catch((error: any) => {
return Observable.throw(this.unwrapHttpError(error));
});
I initially wanted to just make it so that the first .catch and the .map are either/or? (i.e. the .map only runs if the http request is successful), but I'm not sure if that's even possible, and then it was further complicated by my reading the post here where it seems like they may be saying that per this fix, the map method will automatically be skipped if the HTTP code is <200 or >300...? However, that isn't what I'm observing in practice with angular 2.0.0-rc.4...
Many thanks for any assistance!
Think of catch being like typical try and catch code. For an observable, all of the operations will be run in order as if they were in a try block. If there is an error, then processing will jump down to the first catch.
So, if you only want to run the map on success, then you just put it before the catch:
let stream = this.http.request(options.url, options)
.map(this.unwrapHttpValue)
.catch(error: any) => {
this.errorsSubject.next(error);
return Observable.throw(error);
});