Postman response in different order to console log response from request - reactjs

When using Postman to test an API a request, the response i get is unordered, which is what I want, i.e.:
}
"23": "Kevin",
"2": "James",
"12": "Michael"
}
However, when I log the response, it automatically sorts it to:
}
"2": "James",
"12": "Michael",
"23": "Kevin"
}
I am getting the response in a promise:
return this.client.post('/url', data)
.then(response => {
console.log('api response: ', response);
Is there anyway I can prevent the ordering of the response so I can render the data as desired? I am not sure where, or why the order of the data is different.
Any help will be massively appreciated!

You cannot and should not rely on the ordering of elements within a JSON object.
From the JSON specification at http://www.json.org/
An object is an unordered set of name/value pairs
As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit. This is not a bug.

Related

React API call, render data with QuickBase's new RESTful API

I'm trying to figure out what i'm doing wrong here... I've been out of coding for awhile and trying to jump back in for an external application utilizing QuickBase's RESTful API. I'm simply trying to get data from QuickBase to be used outside in an external app to create charts/graphs.
I'm not able to use GET as it gives me only the field names and no data, if I use POST, then I get the values of these fields as well. I'm able to get all the data rendered in the console, but am struggling to get each field rendered to be used in the app.
let headers = {
'QB-Realm-Hostname': 'XXXXXXXXXXXXX.quickbase.com',
'User-Agent': 'FileService_Integration_V2.1',
'Authorization': 'QB-USER-TOKEN XXXXXX_XXXXX_XXXXXXXXXXXXXXXX',
'Content-Type': 'application/json'
}
let body = {"from":"bpz99ram7","select":[3,6,80,81,82,83,86,84,88,89,90,91,92,93,94,95,96,97,98,99,101,103,104,105,106,107,109,111,113,115,120,123,224,225,226,227,228,229,230,231,477,479,480,481],"sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":40,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}
fetch('https://api.quickbase.com/v1/records/query',
{
method: 'POST',
headers: headers,
body: JSON.stringify(body)
})
.then(res => {
if (res.ok) {
return res.json().then(res => console.log(res));
}
return res.json().then(resBody => Promise.reject({status: res.status, ...resBody}));
})
.catch(err => console.log(err))
Hoping to get some help getting the data rendered to be used in React, as well as any tips from anyone who's used QuickBase's new API calls in their realm! And I apologize if it's an easy question/issue, haven't been in React for a couple years... and I'm feeling it!
Thanks!
A successful response from Quickbase for this call has a property data which is an array of the records returned. Each element of this array is an object where the FID for each field returned is a key for nested object - or objects for some field types - with the field's value. Here's a very contrived example:
{
"data": [
{
"1": {
"value": "2020-10-24T23:22:39Z"
},
"2": {
"value": "2020-10-24T23:22:39Z"
},
"3": {
"value": 2643415
}
}
],
"fields": [
{
"id": 1,
"label": "Date Created",
"type": "timestamp"
},
{
"id": 2,
"label": "Date Modified",
"type": "timestamp"
},
{
"id": 3,
"label": "Record ID#",
"type": "recordid"
}
]
}
If you put the data array of the response directly into state with const [quickbaseData, setQuickbaseData] = useState(res.data); for example, you need to keep the structure of the response in mind when accessing that data. If I want to get the value of FID 3 from the first record in the response I would need to use quickbaseData[0]["3"].value. For most field types value will be a string or integer but for some field types it will be an object. You can see the way values are returned for each field type in Field type details.
Depending on your needs you might consider processing the Quickbase response into a new, simpler array/object to use in your application. This is especially helpful if the value being returned needs additional processing such as converting into a Date() object. This would also allow you to make your application API agnostic since other than initially processing the response from Quickbase the rest of your application doesn't have to have any knowledge of how Quickbase returns queried data.
On the Quickbase side of things, there isn't the equivalent of 'SELECT *' so to get data for all fields of a table where you don't know the schema (or it changes frequently) you can run a GET on the Fields endpoint: https://developer.quickbase.com/operation/getFields an then use the field IDs in the response to make the POST call to /records/query

why does this dot notation produce different outputs in axios and express

So I am making a geo tool app using reactjs. The design for this part is this, user submit a city's name. The submission will trigger a post request, and the request will loop through a city list.json file to find the matched city and will return the city's geolocation in such format
{
"id": 6167865,
"name": "Toronto",
"state": "",
"country": "CA",
"coord": {
"lon": -79.416298,
"lat": 43.700111
}
}
the post request at front end is
axios.post('http://localhost:5000/weather/loggedin/citySearch',searchCity)
.then((res)=>{
console.log(res.data.coord)//<--here
})
the post request at server side (backend) is
router.post('/loggedin/citySearch',(req,res)=>{
let cityname = req.body.cityName
let countryname = req.body.country
fs.readFile('../public/weatherdata/citylist.json', (err,data)=>{
if(err){
console.log(err)
res.send('Wrong.')
}else{
user_info.cityName = cityname
let selected_city=(JSON.parse(data)).filter(i=>i.name===cityname && i.country===countryname)
console.log(selected_city[0].coord)//<--and here
res.json(selected_city[0])
}
})
})
Can someone tell me why I get different outputs when using
console.log(res.data.coord) //used at axios and it returns the coordinates
vs.
console.log(res.selected_city[0].coord) //used at server.js and it returns undefined
I was wondering if axios and express take dot notation differently?
Disregard the question
I never put selected_city[0]in my code

Make Axios Limit the Number of Responses

I am attempting to make an axios GET call to an API to retrieve some JSON data. The data is stored in an array with multiple objects each containing the same keys. There are hundreds of objects in this array but I only want to return the first ten. I am aware I can truncate the data set once it is returned but I am wondering if there is a way to limit the amount of responses to my API call.
Here is an example of the data set:
[
{
"userId": 1,
"id": 1,
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald"
},
{
"userId": 1,
"id": 2,
"title": "1984",
"author": "George Orwell"
},
{
"userId": 1,
"id": 3,
"title": "The Count of Monte Cristo",
"author": "Alexandre Dumas"
},
]
and my axios request is simple as well:
router.get('/', (req, res) => {
axios.get(`https://jsonwebsit.info.com/posts`)
.then( response => {
res.send(response.data)
})
.catch(err => {
console.log('Error getting all data from API', err)
})
});
Actually, you can limit the number of responses from a certain API endpoint.
Just add params as an object as a second parameter while making the request.
For example:
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/todos',{
params: {
_limit: 10
}
})
.then((res) => {
this.setState({
todos: res.data
});
})
}
Here you are limiting the response to 10 from jsonplaceholder API.
You could also call https://jsonplaceholder.typicode.com/todos/?_limit=10 and would get the same result.
Hope it helps.
On your side there's nothing you can do until pagination is implemented on API side. Depending on the way it's implemented, you will probably make requests to API sending params like offset, page, limit- these are the most common params' names saying how many elements should API return. But if that's 3rd party provider and their docs are not saying anything about such possibility, you're most likely won't be able to do what you want

How I can read and storage a JSON object from Dynamodb into React?

I am getting a JSON object from a Lambda function. When I get a specific value from the JSON object and storage it into an array it works fine. I don't know how to storage the whole JSON object on any structure in React. The idea is to storage the JSON object to make some calculations later with the values.
I am using "json.map" get the values
Here is where I call the API gateway and fecth the json object:
componentDidMount() {
fetch('https://llzgbat7hi.execute-api.us-east-2.amazonaws.com/api/getrange?domain=demo.com&cont=5')
.then(res => res.json())
.then(json => {
const RecordRowCount = json.map(item => item.RecordRowCount)
this.setState({ tasks: RecordRowCount })
});
}
The code above show how I get the value RecordRowCount and storage it into an array but I need to fecth the whole JSON object
This is the actual JSON structure returned from DB:
[
{
"Id": "123455",
"Customer": 100,
"Domain": "demo.com",
"OrgName": "demo.com",
"ReportMetadataEmail": "demo#me.com",
"ReportMetadataExtraContactInfo": "postmaster#demo.com"
},
{
"Id": "123456",
"Customer": 101,
"Domain": "demo1.com",
"OrgName": "demo1.com",
"ReportMetadataEmail": "demo1#me.com",
"ReportMetadataExtraContactInfo": "postmaster#demo1.com"
}
]
I want to map that JSON object into any React structure (Ex Array)
Thanks a lot #AppleJam, #Taki and #tcoulson
You were right. I just assigned json to tasks and it worked, now my tasks array hold all the json object.
Thanks

fetchMock: uncaught typeError

I have mocked my API-Respones with fetchMock (v.5.13.1). I have been working with it for a quite long time now and I didn't see this kind of behaviour yet.
I mocked two GET responses that are very similar.
fetchMock.get('glob:*/shippings/',"results":[
{"id": "1234", "status": "RELEASED", "foo": "bar"},
{"id": "5678", "status": "CREATED", "foo": "bar"},)
fetchMock.get('glob:*/shipping/myId1234',
{"id": "1234", "status": "RELEASED", "foo": "bar"})
Now, the first one works properly, but the second get returns me this error message:
fetch-mock.js:187 Uncaught TypeError: Invalid status RELEASED passed
on response object. To respond with a JSON object that has status as a
property assign the object to body e.g. {"body": {"status:
"registered"}}
I have an assumption, that I cant mock some response that contains a status, because thats in a way a reserved attribute for status codes, but I am not quite sure and I cant find any similar errors online.
For the second request to fetchMock, it assumes status to be one of the standard codes supplied as an integer. According to the docs, the config supplied to fetchMock expects the following params
If an object only contains properties from among those listed below it
is used to configure a Response to return
body: String | Object
Set the Response body. See the non-config Object section of the docs
below for behaviour when passed an Object
Server responded ok { token: 'abcdef' }
status: Integer
Set the Response status
200, 404, 503
headers: Object
Set the Response headers
{'Content-Type': 'text/html'}
redirectUrl: String
The url from which the Response should claim to originate from (to
imitate followed directs). Will also set redirected: true on the
response
throws: Error
Force fetch to return a Promise rejected with the value of throws
new TypeError('Failed to fetch')
However for a custom status attribute you can respond with a body
fetchMock.get('glob:*/shipping/myId1234', {
body: {"id": "1234", "status": "RELEASED", "foo": "bar"}
})

Resources