Using fetch() with API - 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

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

Storing Api respond inside a variable Ionic

I want to store the respond for my call in variable then use it in my code but if I look at the console I get undefined
getdata(){
return this.http.get<any>('url', { headers: header })
}
this.testProvider.getdata().subscribe(data =>
{this.films=data.name
console.log(this.films);
})
You should dothis.films= data.content.name
Edit: this.films= data.content[index].name

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.

Can't get fetch(url) working in React-Native

I am trying to retrieve the json response from api url using fetch (method : GET) in react-native.
constructor(props){
super(props);
this.state = {jsonData: {}};
}
componentWillMount() {
console.log("inside componentWillMount");
fetch('http://localhost:3000/listData')
.then((response) => {console.log('response: '); return response.json();})
.then((responseJson) => {console.log('responseData: '+JSON.stringify(responseJson)); return this.setState({jsonData: responseJson});})
.catch((err) => {console.log(err)});
}
The api returns data in this format:
{
object: 'list',
data: [...]
}
The api url works via curl. I also tried to run the fetch part of the code standalone using node by installing node-fetch and it printed the responseData properly.
But, in react-native, it doesn't print any of the console log statements inside the then function of fetch nor does it set the state of jsonData.
Could you please tell me what could be the problem? I have been googling around for quite a long time trying to find what could be the issue.
EDIT
I tried the async fetch as follows:
componentWillMount() {
console.log("inside componentWillMount");
this.fetchData().done();
}
async fetchData(){
const response = await fetch('http://localhost:3000/listData')
const json = await response.json();
const data = json.url;
console.log('data'+url);
}
Still, the same issue persists.
I am not able to understand why it works with the facebook url and not my local api url
SOLUTION
Thanks to Michael Cheng for pointing me in the right direction.
I found this link :
https://github.com/react-community/create-react-native-app/issues/154 .
Code Fix:
I just replaced the localhost with my ipv4 address as http://myserveripv4address:3000/listData and it worked.
Version:
react-native#0.50.4
Device : Android
some ideas:
if is iOS, you need the remote url to be https or disable this security feature;
You may need to mark your fetch() as async function;
Try to make an async fetch w/o promise.

React-native Fetch GET, while passing request items to the url

I have a Django-REST API that I am trying to access with a React-native app. I would like to achieve the same result that the command line
http GET http://mywebsite.com/api param1=value1 param2=value2
but using the fetch() function from the networking tutorial. How can I specify the request items to the fetch while using the GET method?
EDIT: my goal is to able to perform a token authentication to a django rest API which need these request item for the page to be accessed.
fetch() uses the exact URL string you provide to perform the request.
Include URL params in your url like when you are calling fetch()
fetch("http://whatever.xyz?param1=1&param2=2")
The simplest way to handle this is by using something similar to the following function
function apiCall() {
return fetch('http://mywebsite.com/api/?param1=value1&param2=value2')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}