Cant read React state data - javascript

I'm developing a react application and in my state I have the data saved that I try to read. When I JSON.stringify the device data "console.log"'it out, look like this:
{
"ActTime": 1509988664,
"ServerTime": "2017-11-06 18:17:44",
"Sunrise": "07:25",
"Sunset": "15:53",
"result": [
{
"AddjMulti": 1,
"AddjMulti2": 1,
"AddjValue": 0,
"AddjValue2": 0,
"BatteryLevel": 255,
"CustomImage": 0,
"Data": "On",
"Description": "",
"Favorite": 1,
"HardwareID": 2,
"HardwareName": "Controller",
"HardwareType": "OpenZWave USB",
"HardwareTypeVal": 21,
"HaveDimmer": true,
"HaveGroupCmd": true,
"HaveTimeout": false,
"ID": "00000501",
"Image": "Light",
"IsSubDevice": false,
"LastUpdate": "2017-11-06 15:42:00",
"Level": 0,
"LevelInt": 0,
"MaxDimLevel": 100,
"Name": "Vardagsrum",
"Notifications": "false",
"PlanID": "0",
"PlanIDs": [
0
],
"Protected": false,
"ShowNotifications": true,
"SignalLevel": "-",
"Status": "On",
"StrParam1": "",
"StrParam2": "",
"SubType": "Switch",
"SwitchType": "On/Off",
"SwitchTypeVal": 0,
"Timers": "false",
"Type": "Light/Switch",
"TypeImg": "lightbulb",
"Unit": 1,
"Used": 1,
"UsedByCamera": false,
"XOffset": "0",
"YOffset": "0",
"idx": "3"
}
],
"status": "OK",
"title": "Devices"
}
If I want to read the status data I just do: device['status'] I get "OK", but what if I want to access the result data in the device?
I thought that device['result'][0]['Status'] would give my 'Ok, but I just get Uncaught TypeError: Cannot read property '0' of undefined ???
How do I read the result data in the device??

To do this device['result'][0]['Status'] you want to ensure your device data is not a string but a proper JSON object. You could JSON.parse() to convert it if it's not already an object.
Also ensure the data is available before trying that.

Try to use map method over result array.
Something like this:
result.map((item,index)=>{
console.log(item[index].AddjMulti);
})

Related

Javascript axios get json array with a bigint

I get an array from the API as follows:
[ { "URL": "", "avatar": "", "characterID": 853, "creationDate": "2022-01-22T17:12:42", "description": "description", "foreignSuggestionID": 0, "id": 5, "seriesID": 0, "type": "IMAGE", "userID": 168314031248113660 } ]
However I expect
[ { "URL": "", "avatar": "", "characterID": 853, "creationDate": "2022-01-22T17:12:42", "description": "description", "foreignSuggestionID": 0, "id": 5, "seriesID": 0, "type": "IMAGE", "userID": 168314031248113664} ]
The userID gets transformed in the request by Javascript, since when I use transformResponse: data => data I get the correct ID.
This gets me to the conclusion that it cannot contain the large number in Javascript. My question here would be, is there a way to make sure that a specific value within the json array is seen as a bigint or can I convert the column into a string on receiving the response?
I use axios and my code is as follows:
this.$axios.get(url, {
withCredentials: 'true'
})
.then(response => {
this.data = response.data
})

Pass data in React FullCalendar with API call

I'm getting some data with an API call and Data looks like this
{
"events": [
{
"id": 7,
"comments": "",
"origin": "Terrassa, Spain",
"destination": "Delft, Netherlands",
"total_trucks": 0,
"material_type": "0",
"scheduled_date": "2019-09-29T01:01:00",
"offered_price": 0,
"weight": 7979879,
"status": "Assigned",
"posted_on": "2019-09-23T15:24:39.946644",
"All_India": true,
"Andhra_Pradesh": false,
"Assam": false,
"Bihar": false,
...
"West_Bengal": false,
"owner": 1,
"truck_type": 2,
"truck_name": 139
}
{
"id": 9,
"comments": "",
"origin": "Teyty, Spain",
"destination": "Derry, Netherlands",
"total_trucks": 0,
"material_type": "0",
"scheduled_date": "2019-09-29T01:01:00",
"offered_price": 0,
"weight": 7979879,
"status": "Assigned",
"posted_on": "2019-09-23T15:24:39.946644",
"All_India": true,
"Andhra_Pradesh": false,
"Assam": false,
"Bihar": false,
...
"West_Bengal": false,
"owner": 1,
"truck_type": 2,
"truck_name": 139
}
]
}
From this data I want schedule_date in 'date' field in my events of reactFullCalender and total_weight and total_trucks in title of those event.
What I've tried so far gives me output as Object object in events on calendar screen.
My code for that is:
<FullCalendar defaultView="dayGridMonth" plugins={[ dayGridPlugin ]}
events={[{ title: this.state.calendarEvents, date: '2019-09-22'] />
And my API call looks like this:
const calendarEvent = await getEventsData();
this.setState({calendarEvents:calendarEvent});
console.log(calendarEvent,
"calendarEvents");
And my states looks like this:
this.state = {
calendarEvents:[
{totalTrucks:''},
{totalWeight:''}]};}
All I want is that API call calendarEvent gets the data and I want to feed that in events in fullCalender
Can you use this:
setStateAsync(state) {
return new Promise((resolve) => {
this.setState(state, resolve)
});
To set your state asynchronously after we get it from the data.
This has a reference where we set State asynchronously.

Find and replace key in Javascript object

I'm accessing a JSON that comes back looking like this:
[
{
"itemType": "SelectionTitle",
"name": "1105F.MID",
"active": true,
"isFactoryDefault": false,
"factoryCode": "",
"seasons": [],
"denominations": [],
"groups": [],
"length": 0,
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"itemType": "SelectionFile",
"name": "1105F.MID",
"active": true,
"isFactoryDefault": false,
"selectionType": "Music",
"sfzFile": "",
"destination": "/data/uploads",
"encoding": "7bit",
"fieldname": "file",
"filename": "782f49a7cd72b865b4e2d286816792e7",
...
"found": true,
"flError": false,
"error_strings": [],
"_id": "5ada2217c114ca048e1db9af",
"created_by": "5ab57289d8d00507b29a3fdd",
"slug": "1105fmid",
"__v": 0,
"createdAt": "2018-04-20T17:23:35.216Z",
"updatedAt": "2018-04-20T17:23:35.788Z",
"selectionTitles": null,
"id": "5ada2217c114ca048e1db9af"
},
"slug": "1105fmid",
"createdAt": "2018-04-20T17:23:35.285Z",
"updatedAt": "2018-04-20T17:23:35.285Z",
"__v": 0,
"id": "5ada2217c114ca048e1db9b0"
}, ...
The react-select node module that I am using takes the key "label" to generate a populated dropdown.
The JSON is coming from the web so I can't control how the JSON is setup. How do I parse the JSON to find all the instances of "name" and replace that key with "label" ?
For example "name" : 1105F.MID" should be changed to "label" : "1105.MID"
Would it be inefficient to convert the entire thing to a string and use the javascript method find/replace?
Assuming your JSON array is stored in the variable data:
data.forEach(item => item.label = item.name)
This would be sufficient to duplicate the name property as the label property for each item in the array.
I have created a function replace() to deal with every object and nested objects, which will add property 'label' if 'name' property is found. Pls see if it's useful to you.
var arr = [
{
"itemType": "SelectionTitle",
"name": "1105F.MID",
"active": true,
"isFactoryDefault": false,
"factoryCode": "",
"seasons": [],
"denominations": [],
"groups": [],
"length": 0,
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"itemType": "SelectionFile",
"name": "1105F.MID"
}
},
{
"itemType": "SelectionTitle",
"name": "test",
"active": true,
"isFactoryDefault": false,
"factoryCode": "",
"seasons": [],
"denominations": [],
"groups": [],
"length": 0,
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"itemType": "SelectionFile",
"name": "testing"
}
}
]
// this method will take care of adding new property
function replace(obj, from, to) {
Object.entries(obj).forEach(([key, value]) => (
key == from && (obj[to] = obj[from])
, typeof value === "object" && replace(value, from, to)
))
}
arr.forEach(d => replace(d, 'name', 'label'))
// you can check this log for property 'label' whereever 'name' exists
console.log(arr)
Relying on the structure of server response is bad; especially when you say you have not control over it. A better way would be to always parse the server response, construct whatever necessary for the react-select component to work and pass that only.

Assign array of JSON objects to array of interface Angular/Typescript

Currently, this works and doesn't give my error while running but my text editor is giving me an error that says property 'categories' does not exist on type 'CategoryInterface[]' (on the line where response.categories is assigned to variable) so I'm not sure if I'm doing things right.
public categories: CategoryInterface[];
.subscribe((response: CategoryInterface[]) => {
this.categories = response.categories;
console.log(this.categories);
});
My backend returns this:
{
"categories": [
{
"categoryId": 1,
"name": "Important",
"description": "This category is important.",
"order": 1,
"createdBy": null,
"createdAt": "2017-11-25 12:09:04",
"updatedBy": null,
"updatedAt": "2018-01-17 23:53:25",
"categoryBoards": [
{
"categoryBoardId": 1,
"categoryId": 1,
"name": "Announcements",
"description": null,
"order": 2,
"createdBy": null,
"createdAt": "2017-11-25 12:09:49",
"updatedBy": null,
"updatedAt": "2018-01-18 00:09:02"
},
{
"categoryBoardId": 23,
"categoryId": 1,
"name": "Rules",
"description": null,
"order": 1,
"createdBy": null,
"createdAt": "2018-01-18 00:08:57",
"updatedBy": null,
"updatedAt": "2018-01-19 00:05:51"
}
]
}
]
}
You are trying to cast your api response to an array of CategoryInterface which is not the case, you better use your subscribe method like this:
.subscribe((response: any) => {
this.categories = <CategoryInterface[]> response.categories;
console.log(this.categories);
});
It's the your api response categories which needs to be casted to CategoryInterface[]
Bonus: The angular style-guide notice that you need to declare classes instead of interfaces and you don't have to suffix the class name with Interface, so just name your CategoryInterface to Category.
You get the error because you declare response as a CategoryInterface[], but response.categories is actually the CategoryInterface[]. response is just a wrapper around the array. All the types are stripped out when the typescript is converted to javascript, which is why it works fine at runtime.

Trying to get a deeply embedded object from API object in JavaScript

I am trying to pull out the "quantity" value out of this API call with JavaScript however I cant seem to wrap my mind around it. Does any one feel up for the challenge?
{
"count": 5,
"results": [{
"listing_id": 216653218,
"state": "active",
"user_id": 57517426,
"category_id": 69150359,
"title": "Foodie Dice",
"description": "Some discription.",
"creation_tsz": 1419964059,
"ending_tsz": 1430414859,
"original_creation_tsz": 1419964059,
"last_modified_tsz": 1420033299,
"price": "25.00",
"currency_code": "USD",
"**quantity**": 1,
"tags": [],
"category_path": ["Geekery"],
"category_path_ids": [69150359],
"materials": [],
"shop_section_id": null,
"featured_rank": null,
"state_tsz": 1419964059,
"url": "https://www.etsy.com/listing/216653218/foodie-dice?utm_source=buddhabar&utm_medium=api&utm_campaign=api",
"views": 1,
"num_favorers": 0,
"shipping_template_id": null,
"processing_min": 1,
"processing_max": 1,
"who_made": "i_did",
"is_supply": "false",
"when_made": "2010_2015",
"is_private": false,
"recipient": null,
"occasion": null,
"style": null,
"non_taxable": false,
"is_customizable": false,
"is_digital": false,
"file_data": "",
"language": "en-US",
"has_variations": false,
"used_manufacturer": false,
"MainImage": {
"listing_image_id": 704444582,
"hex_code": null,
"red": null,
"green": null,
"blue": null,
"hue": null,
"saturation": null,
"brightness": null,
"is_black_and_white": null,
"creation_tsz": null,
"listing_id": 216653218,
"rank": null,
"url_75x75": "https://img0.etsystatic.com/048/0/10392050/il_75x75.704444582_poqv.jpg",
"url_170x135": "https://img0.etsystatic.com/048/0/10392050/il_170x135.704444582_poqv.jpg",
"url_570xN": "https://img0.etsystatic.com/048/0/10392050/il_570xN.704444582_poqv.jpg",
"url_fullxfull": "https://img0.etsystatic.com/048/0/10392050/il_fullxfull.704444582_poqv.jpg",
"full_height": null,
"full_width": null
}
},
Use a tool to beautify the output, it helps a lot.
One such tool here http://jsbeautifier.org/
As far as your question, you can access it here:
data.results[0].quantity

Categories