Dealing with data in axios response - javascript

I'm new to axios.
In the past when I've made http requests I'm used to getting back an array/array of objects and this allows me to easily format the data how I want by using functions such as map and reduce. I then would render it to the DOM.
I've noticed in the response I get back is an observer object. How would I go about making the request so it gives me back an array? What is the standard for dealing with this observer object?
getSomething (myId) {
return axios.get('/api/getSomething', {params: {'id': myId}})
.then(response => console.log(response.data))
.catch((promise) => this.handleError(promise));
}
Thanks
EDIT:
Updated code.
To clarify, when I call getSomething() response.data is an object even though I am sending it as an array on the backend. I am assuming that axios is changing this array to an object. The object has a bunch of extra properties like __ob__ and get 0

So I found the issue. If you pass through an array where the keys are not in order e.g. [1: [], 5: [], 6:[]]. Javascript will change it into a observer object which has different properties in order to maintain the keys. This issue is not related to axios.

You can do something as simple as the following to access the data:
axios.get('/some/url').then(response => {
console.log(response);
});

Related

Call a specific array in a JSON API call

I'm trying to call the API but it doesn't return me anything.
I'm calling it like: res.on('data', d => { const RetrieveFromApi = JSON.parse(d).FLUX.quote.USD.price;.
The API is successfully called since I can see it in the API history, and data is defined as d.
Can you help me please?
from your screen provided in comment, you passed one property you don't access to it which is data
So just add property data before FLUX
JSON.parse(d).FLUX.quote.USD.price;
^data.FLUX.quote.USD.price;
From the image of the log the object seems incomplete at the end, did you try to use JSON.stringify(d) to see if there are any errors on the json object? or copy the response on https://jsonlint.com to check?
Because the error message points that the parse doesn't find a valid json object, maybe that is the whole point.
And the other tip is to try to store the value of JSON.parse in an variable before trying to access his values.

Formatting a JSON Response to build a URL

I'm incredibly stuck on trying to format receive a JSON response, and format it. Order of operations:
Query a REST API endpoint (https://endpoint.com/api/v1/employee?id={username})
Receive JSON response: {"employee":{"full name":"Example Name","function":"Role","office":"Office Location",team":"Team 1|Team 2|Team 3|"}}
In my base.js file within my django app, I am hoping to extract the team strings and pass them into another URL. What way can I do this? When I $.getJSON from the endpoint I receive responseJSON, responseText, etc. but I'm unable to pull them out/use them in any way.
In order to fetch and parse json I would suggest you to use the following fetch structure:
fetch('https://endpoint.com/api/v1/employee?id=username')
.then(response => response.json())
.then(data => {
let teams = data.team.split('|');
// Do something with team names
});
Let's break down what this does per line:
First we use fetch to request data from the defined url
Then we convert the response to a json object
Finally we retrieve the string with team values using the data.teams statement, after which we immediately convert the list of team names to an array by using split and the defined delimiter |.
After this you should be able to do whatever you'd like with the team names. You could use them to make another API call as well. If you're interested, be sure to checkout the fetch documentation, as well as the split documentation if you are not yet familiar with that function.
The solution above assumes that the response will be a 200, for error handling you should check out the fetch documentation above.

How to get the right answer form in axios

I use axios, the answer to my query comes in the form of response.data.response.object. How can I get an answer without response.data immediately response.object??
You cannot achieve what you want like that, axios returns the body of the response from within the data object.
Although, you can do this:
let response = response.data.response;
And then you can use response.object
EDIT: As stated in the other answer, this is definitely doable, although I would advise against manipulating the structure in which axios sends its response as this makes assumptions about the structure of the JSON response. (especially if being setup as a global setting)
axios.defaults.transformResponse = [function (data) {
// Do whatever you want to transform the data
return JSON.parse(data).response.object;
}],
then now you can access to your object by just typing: response.data
It's work
export function name(param) {
return axios.get(`URL`,
{transformResponse: axios.defaults.transformResponse.concat((response) => {
return response.response
})
}
)}

Parse Server Upset Data in loop

I'm trying to query an API to get some data then I want to upsert all of it into my table.
But for some reason I'm not having any luck.
What's the best way to go about this?
I don't think my method of doing a query in a loop is best.
var coin = new Parse.Object.extend("Coins");
axios.get('https://api.coinmarketcap.com/v1/ticker/')
.then(response => {
let data = response.data;
// Put into database
data.map(entry => {
let q = new Parse.Query(Model.Coins.className());
q.equalTo('symbol', entry.symbol);
q.first()
.then(record => {
record.set('symbol', entry.symbol);
record.set('price_usd', entry.price_usd);
return record.save(null, {useMasterKey: true});
});
});
res.success(response);
});
you should avoid fetching and updating objects in a loop. In order to make it better you need to use 2 things:
In your query, instead of using equalTo and first you need to use containedIn for query all the records in one call. Then you need to iterate on the query results, for each record in the loop you need to do the following:
record.set('symbol', entry.symbol);
record.set('price_usd', entry.price_usd);
Finally you need to use saveAll to save all the objects in one call (please notice that saveAll is static function of Parse.Object and you should pass an array into it. Please review the docs before doing it)
Check your data. You may find you have unexpectedly updated records.
Assuming that's the entire body of a cloud function, your function initiates an asynchronous server call, then immediately tells the requestor that the operation was successful, but response isn't populated yet so you pass back undefined. However, parse-server will still run that asynchronous code.
The solution is to put the res.success call inside another .then chain, so the function won't return a response until after the server call + save finishes.
You're also going to get an uncaught error if the symbol doesn't exist on your table, though. You don't check to make sure the query returned a response to the first() call.

How to get data from multiple url's in Reactjs?

I want to get json data from multiple url's and display it on frontend.
Following are the url's:
1) localhost:3000/api/getdata1
2) localhost:3000/api/getdata2
3) localhost:3000/api/getdata3
Instead of using .fetch() on each of the url's like below:
.fetch('localhost:3000/api/getdata1')
.fetch('localhost:3000/api/getdata2')
.fetch('localhost:3000/api/getdata3')
Can this be done in more efficent way in ReactJs ?
I was trying:
const dataurls = [
'localhost:3000/api/getdata1',
'localhost:3000/api/getdata2',
'localhost:3000/api/getdata3'
];
const promisedurl = dataurls.map(httpGet);
Promise.all(promisedurls)
.then(data=> {
for (const d of data) {
console.log(d);
}
})
.catch(reason => {
// Receives first rejection among the Promises
});
Please suggest which one should be used or is there any efficient way to do get data from multiple url's.
ReactJS is a View layer library. It has nothing to do with how you aquire any data from server.
Even state libraries, like Redux and Reflux do not implement any method of fetching data. In most cases you do that in your custom app code. Sometimes using extra libraries (e.g. Redux middlewares).
So, yes: your Promise.all(<several https requests here>) is the most natural way to achieve that.

Categories

Resources