I am trying to make an api call using fetch method in react-native.
I have rn-fetch-blob for uploading images in one screen which is on another different screen. This particular function was for me to initiate a payment online using paystack. though the issue is not about the paystack because this worked in a new project without having rn-fetch-blob in it.
Secondly if i remove response.json(), it wouldn't return anything but there wouldn't be any error. but with response.json(), if get this error
attempt to invoke interface method 'java.lang.bridge.readablemap. getstring(java.lang.string)' on a null object reference.
I suspect there is a conflict between rn-fetch-blob and fetch because even without using rn-fetch-blob, it runs through perfectly, if i do
fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
})
same error comes
i expect a reference value like hyhjgbhgfh
attempt to invoke interface method 'java.lang.bridge.readablemap. getstring(java.lang.string)' on a null object reference.
I logged out response and i saw
Related
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
I'm using Dyson to host a little mock server for my React Native app, and trying to fetch from the server. The server appears to be running well and when I visit my desired url, http://localhost:3000/stations, in my browser, I get a nice JSON response.
In my React Native action, though, I get Network request failed:
export function fetchStations() {
return dispatch => {
dispatch({ type: "GET_STATIONS_START" });
fetch("http://localhost:3000/stations")
.then(res => {
return res.json();
})
.then(json => {
dispatch({ type: "GET_STATIONS_SUCCESS", payload: json.stations });
})
.catch(error => {
console.warn(error);
dispatch({ type: "GET_STATIONS_FAILURE", payload: error });
});
};
}
Using a static local URL works, and using, say, the Google Maps API works (even though it's not what I want, it's just a sample API to try).
I would think I may be calling the url wrong but it works in the browser so that seems doubtful. My guess is that is has something to do with iOS not liking http requests (only accepting https), unless you set some setting somewhere (I've been through this in native iOS development).
If this is the problem, how do I fix it from React Native? Or, what is the actual problem?
PS. I'm using dyson rather than json-server because for some reason I can't get json-server to work. See my other post. Somewhere here :)
I figured it out. The device (simulator) doesn't have access to localhost so I had to set my url to http://127.0.0.1:3000/stations and it works like a dream.
My fetch returns this promise which works for other fields in the API but I need to save the value for a field within that has the name "datasets-pollencheck_apiaries" however react-native inteprets the "-" as something else and I can't access this field, and continually get the error that says "Can't find variable: pollencheck_apiaries"
.then((response) => response.json())
.then((responseJson) => {
LINK = responseJson.links.datasets-pollencheck_apiaries;
})
Any insight would be much appreciated.
This is because JavaScript thinks you're trying to do a math operation. You can also access object properties with bracket notation.
You should try this:
LINK = responseJson.links['datasets-pollencheck_apiaries']
Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
try to change to
.then((response) => response.json())
.then((responseJson) => {
LINK = responseJson.links["datasets-pollencheck_apiaries"];
})
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.
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¶m2=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¶m2=value2')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}