How do i retrive the city name from opengatedata.com - react-native

'''if (await permission()) {
Geolocation.getCurrentPosition(
async position => {
await fetch(
`https://api.opencagedata.com/geocode/v1/json?q=${position.coords.latitude}+${position.coords.longitude}&key=apikey&pretty=1`,
).then(result => {
console.log(result.data);
});
},
error => {
console.log(error.code, error.message);
},
);
}'''
How do i retrive the returned location from the response sent to me
The things it sends me seems like gibrish and have no clue what to do and i am building the app in react-native using tsx

All you need to do is console the response to make sure that you are receiving your response as expected after that you've multiple choices to extract the required data e.g. Destructuring or looping through the response (quite expensive + time taking) or you can use the filter method, in a nutshell, there are tons of way to get your required data from the response and it's just a matter of your taste(like whichever you prefer)

Related

Making multiple api requests at once using fetch in vue

I would like to make two api call's at once to a ReST API in my vue component. I have done research online and am using this logic:
// Multiple fetches
Promise.all([
fetch(
`https://api.covid19api.com/live/country/${this.selected}/status/confirmed/date/${this.yesterday}`
),
fetch(
`https://api.covid19api.com/live/country/south-africa/status/confirmed/date/2020-03-21T13:13:30Z`
)
])
.then(responses => {
// Get a JSON object from each of the responses
return responses.map(response => {
return response.json();
});
})
.then(data => {
// Log the data to the console
// You would do something with both sets of data here
this.coronaVirusStats1 = data[0];
console.log(this.coronaVirusStats1);
})
.catch(function(error) {
// if there's an error, log it
console.log(error);
});
}
The consoled value is a promise which I understand but when I look in the Vue devTools under my component I see that coronaVirusStats1 has a value of "Promise", not the array of objects I expect back. When I do a single fetch and consume the data variable there is no problem. However I am perplexed as to how one accesses the returned data from fetch calls to multiple endpoints. I tried all the solutions here fetching api's ,but none worked. If someone can elucidate on the proper way to access the data from the fetches I would be most appreciative.
You're just about there. The issue is that your first then returns an array of promises. Unfortunately, promise chains only work with a Promise instance so there's nothing here that will wait for your promises to resolve.
The quick fix is to change the first then to
return Promise.all(responses.map(r => r.json()))
That being said, there's a little more to the fetch API, particularly for dealing with errors.
I would use something like the following for each fetch call to make sure network errors and non-successful HTTP requests are handled correctly.
This will also handle unwrapping the JSON response so you don't have to use the above
Promise.all([
fetch(url1).then(res => res.ok && res.json() || Promise.reject(res)),
fetch(url2).then(res => res.ok && res.json() || Promise.reject(res))
]).then(data => {
// handle data array here
})
See https://developer.mozilla.org/en-US/docs/Web/API/Response/ok

Using fetch() with API

I try to use fetch() to get the data from https://swapi.co/
With this code I get undefined but in the "Network" section in chrome I see the data I need. How I can access it?
fetch('https://swapi.co/api/people/1/')
.then(resp => resp.json)
.then(obj => console.log(obj));
Hello this will fetch the data returning it as json
fetch('https://swapi.co/api/people/1')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
If you have right environment for calling to the fetch API there maybe 2 result
You will get the right result data
You will get an error
fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function() {
// Your code for handling the data you get from the API
})
.catch (function() {
// This is where you run code if the server returns any errors
});
Use a catch for seen what is going wrong with your request

VUE: Issues with fetching data when I use Pagination

I have a a set of data which I can access for the first page. But as soon as I use the pagination and trying to press next page, then I can't access the data. I get the 401 issue.
created(){
this.fetchNotater();
},
methods: {
fetchNotater(page_url){
let vm = this;
// api/borgernotater works perfectly. But when I use the page_url then it won't accept my api_token
page_url = page_url || 'api/borgernotater';
fetch(`${page_url}?api_token=${window.Laravel.apiToken}`)
.then(res => res.json())
.then(res => {
this.notater = res.data;
vm.makePagination(res);
})
.catch(err => console.log(err))
},
makePagination(res){
let pagination = {
current_page: res.current_page,
last_page: res.last_page,
next_page_url: res.next_page_url,
prev_page_url: res.prev_page_url
};
this.pagination = pagination;
}
You have a typo in your API request URL construction: parameters need to be separated with &. You can see that when you are requesting page 2, you have two questions marks in your URL and that’s an invalid query string, and the API request URL will not be parsed correctly. It should be: ?page=2&api_key=....
With that in mind, it might be helpful to use a third party library, like query-string on NPM, to perform parsing and adding payload to your query string.

Call API with Another Api response data in Nuxtjs

Im making a website with Nuxtjs, i want when i open any page of the website to get user information from the server using Axios, and i want to use these information to call another API's from the website.
For example: i will get the User id and Client id from the server and use them on the API URL, lets say i got User id = 5, Client id = 10
i will call another API's and use these informations
http://****/getItems?userid=5&clientid=10
Now my problem is the second API call before the first API finished so i didn't got the user informations yet.
Could you please help me with this issue, note that i want to get the user information on all pages. so if i reload the page in any page i want to get user informations.
So i call the user information API from a Layout and call the other API's from another components.
Thanks.
First you should use Axios module officially provided by Nuxt.js here, https://github.com/nuxt-community/axios-module. They have make the integration between Axios and Nuxt.js easier.
Axios uses promise so you can easily chaining method to do it. Let say you wanna get information from /get/product with data gotten from the url you mention before http://****/getItems?userid=5&clientid=10, you can easily do that like this
this.$axios.$get('/getItems?userid=5&clientid=10')
.then(data => {
// You can use your data received from first request here.
return this.$axios.$post('/get/product', {
id: data.id,
clientId: data.clientId
})
})
.then(data => {
// You can use your data received from second request here.
console.log(data)
})
Explanation
This part,
this.$axios.$get('/getItems?userid=5&clientid=10')
the axios will get the data from the url provided, when the data is received, we can use it within then() block as it accept callback as a parameter.
.then(data => {
// You can use your data received from first url here.
...
})
After that, if you wanna use your data you can easily return the axios request again with proper parameter you wanna send.
return this.$axios.$post('/get/product', {
id: data.id,
clientId: data.clientId
})
And again you can use the data received from second axios request within then() block.
.then(data => {
// You can use your data received from second request here.
console.log(data)
})
Updated
Oke, based on the clarification on the comment section below. We can return the axios promise in first action and then on the second method we can dispatch the first action,
actions: {
callFirst ({ commit }) {
return this.$axios.$get('/get/first')
.then(firstResult => {
commit('SET_FIRST', firstResult)
return firstResult
})
},
callSecond ({ dispatch, commit }) {
return dispatch('callFirst').then(firstResult => {
return this.$axios.$post(`/get/${firstResult.userId}`)
.then(secondResult => {
commit('SET_SECOND', secondResult)
return secondResult
})
})
}
}
Using that way, you just need to put the callSecond() action whereever you want get the second data. And you also don't need to put the callFirst() action on default.vue.

How do I unit test rendering views in Express?

my controller queries an API on another server I've already tested and it works correctly. I'm curious how I would go about testing this controller, all it does is fetch the api data and render it. I've already tested and verified that my api works with chai-http so how does one correctly unit test this?
function(req, res){
rp(http://www.foobar.com/api/posts)
.then(function(posts){
res.render('view', { data : posts } );
})
.catch(function(err){
next(err);
})
}
I'm using Tape as opposed to mocha/chai, but my approach might help you.
I just assert that the response includes the text I am expecting.
test('Post /auth/login renders an error raised by the api service', (t) => {
let spy = sinon.spy();
let mock = sinon.stub(api, 'doLogin')
.resolves({dataForView: 'great success'});
request(app)
.post('/auth/login')
.expect(200)
.end((err, res) => {
t.ok(res.text.includes('great success'));
t.end();
mock.restore();
});
});
The key part is the t.ok(res.text.includes('great success'));. I don't bother asserting that my entire view is rendered as expected, just that any data I am passing into the render call actually ends up in the response.