React unable to render object property - reactjs

I'm attempting to render the values of props object, When I console.log stats object, chrome dev tools console shows the following object.
Object
_id : "vFgY3YBrLj3Pd7zNA"
active: 652668928
available: 595034112
createdAt: Fri Jan 13 2017 03:56:04 GMT+0400 (GST)
free: 595034112
inactive: 563294208
ownerId: "6Kv93sJdY62iGiCwg"
percent : 86.1
However when I attempt to access .stats property I get undefined
console.log(this.props.stats._id);
Uncaught TypeError: Cannot read property '_id' of undefined
Any idea on what I'm going wrong here?

Check this jsfiddle, how to pass props values from parent component and use in child component : https://jsfiddle.net/r7ym0x4r/

I have noticed that this behavior happens because the object is not fully instantiated
In my case the query to fetch object data was slow, here is an example for fetching last record
Stats.findOne({}, {sort: {DateTime: -1, limit: 1}});
And when I changed it to something like, it worked fine.
Stats.find({}).fetch();

Related

Getting array value inside nested object React Redux

I have an object with an array inside it. Object is returned from MongoDB.
{
brand: "OPEL",
createdAt: "2022-12-17T17:44:31.693Z",
image: [
{
public_id: 41658465461,
url: http://www.cloudinary.com,
},
],
licensePlate: "DR126",
mileage: 526,
model: "corsa",
qrCode: "#21566",
updatedAt: "2022-12-17T17:44:31.693Z",
_id: "639dffff33060ff5c3c796eb",
}
The problem is whenever I try to get the image url in my React component obj.image[0].url it returns an error TypeError: Cannot read properties of undefined (reading '0')
console.log(obj.image[0].url) returns undefined
After refreshing page returns 2 logs:
console.log(obj.image[0].url) returns undefined
console.log(obj.image[0].url) returns "http://www.cloudinary.com" (actual link)
I assume that object is not ready before I am trying to access it.
I looked over everyone and couldn't understand where is the issue and how can I solve it.
Thank you in advance for taking a look at this !
Tried forEach() loop, found 1 solution at stackoverflow didn't do the trick in my case.
change obj.image[0].url to obj?.image[0]?.url
the ? checks if the field exists and is not undefined then access to it

Create react immutable JS nested state

I am trying to combine some of my flat state settings into a settings state object, and at the same time, I want to convert this object to a immutable JS state object.
I get errors though that my key is not defined, although I have set the initial state in the constructor.
Here is what I have so far:
constructor() {
super();
this.state = {
"settings": Immutable.Map()
};
}
Then in componentWillMount (since I get the data from an external API):
componentWillMount() {
/* Some code */
this.setState({
settings: settings.setIn({airlines: Immutable.fromJS(airlines).toList()}),
});
}
The error I get is: Uncaught ReferenceError: settings is not defined
Btw. the airlines element is an array of objects
Can someone help me out? Is my approach directionally right? And do I need to use updateIn afterwards (on update) once the airlines array is first set and I need to update, or is it safer to use setIn?
As the error says, settings is not defined at this position.
Instead, refer to the settings slice of your state:
this.setState({
settings: this.state.settings.setIn({airlines: Immutable.fromJS(airlines).toList()}),
});
Edit:
You are also using ImmutableJS' setIn function incorrectly:
this.setState({
settings: this.state.settings.setIn(['airlines'], Immutable.fromJS(airlines).toList()),
});
See the docs or this SO answer for more details.
settings needs to be referenced like this.state.settings.setIn...

When accessing model object property I get error undefined

When I want to use model like this:
console.log($scope.selectedMonth);
I get output:
Object { no: "02", name: "Veljača", $$hashKey: "object:24" }
But when I want to use one of its properties like this:
console.log($scope.selectedMonth.name);
I get error:
Error: $scope.selectedMonth is undefined
Why is that happening and how do I access model object properties?
When object was initialized it was undefined by default. This line of code is inside $watch method and I added if statement that fixed the problem.
if ($scope.selectedMonth !== undefined) {
console.log($scope.selectedMonth.name);
}

Firebase Key/Value access not working

I have the following data setup in firebase.
{
"data": {
"lava14mod1":"down",
"lava14mod2":"up"
}
}
I'm able to access it in my React app. But I can only access it as a (key,value) pair combined as one string.
I cannot access the key or value separately using,
<li>{this.state.data[0]['.key']}</li>
I'm getting this error,
Uncaught TypeError: Cannot read property '.key' of undefined
Uncaught TypeError: Cannot read property '_currentElement' of null
Here's the full code, running on plunker, (without the error line)
http://plnkr.co/edit/zjFKsYAzfYrzGmedVEV6?p=preview
I've been pouring through the docs and still can't figure this out. I'm following the data structure shown in firebase docs,
[
{
".key": "-Jtjl482BaXBCI7brMT8",
".value": 100
},
{
".key": "-Jtjl6tmqjNeAnQvyD4l",
"first": "Fred"
"last": "Flintstone"
},
{
".key": "-JtjlAXoQ3VAoNiJcka9",
".value": "foo"
}
]
Firebase documentation
Is there some problem with my syntax? How do I access the key or value separately?
Thank you so much.
You're getting that error because the this.state.data object does not have the keys you're trying to access in render.
This is easy to see if you simply put a console.log(this.state.data) in render. Doing so gives me something like this in the console:
> []
> [Object]
> [Object, Object]
> [Object, Object, Object]
So, render is being called four different times, once each time that this.state.data is being updated with a new key. But, in your render, you don't consider the fact that keys [0] and [1] might not exist - you try to access them without checking them first.
Now I'm not sure exactly why your state is being updated piecemeal, but it probably has something to do with the ReactFireMixin which I have no experience with. Fetching form Firebase is clearly an asynchronous action (since you have to grab data from the cloud) so you need to make accommodations for that.
The most straightforward fix is simply checking to make sure that the key you want to access actually exists on an object before you try to access it (which is a good practice in most cases to avoid exactly this kind of error!)
render: function() {
return (
<div>
from firebase,
{this.state.data ? <li>{this.state.data}</li> : undefined}
{this.state.data && this.state.data[0] && this.state.data[0][".key"] ? <li>{this.state.data[0][".key"]}</li> : undefined}
{this.state.data && this.state.data[1] && this.state.data[1][".key"] ? <li>{this.state.data[1][".key"]}</li> : undefined}
local var,
<li>{data2[0]['.key']}</li>
</div>
);
}
http://plnkr.co/edit/7XXaOIQCQcyGneqEqa88?p=preview
An even better solution would be to use Array.map to convert whatever array this.state.data is at the time directly into some kind of list. This is a very common pattern in React applications because you'll often keep lists of data as arrays and then want to display it dynamically.
render: function() {
return (
<div>
from firebase,
{this.state.data.map(function(ea){return <li>Key: <strong>{ea[".key"]}</strong>, Value: <strong>{ea[".value"]}</strong></li>})}
local var,
<li>{data2[0]['.key']}</li>
</div>
);
}
http://plnkr.co/edit/b1j10M1i635hvapFxZbG?p=preview
More about Array.map()

Underscore collection pluck returning undefineds [duplicate]

Hi im trying to output every "lat" field from my collection. However anything i do returns the right number of results but they all say undefined, the data is definitely there and the names are definitely right. I've tried using pluck and _.each with a get inside the function and all it ever says is undefined.
This is the current method im trying
var ccLocal = window.router.carsCollection;
_.each(ccLocal.models, function(model) {
console.log(model.lat);
})
logging ccLocal returns the entire collection with all its data so its definitely there. What am i doing wrong?
Using model.get("lat") also fails.
Using console.log(ccLocal.at(0).attributes); returns this
Object {unitID: "03_Cow_30", positionHistory: Array[1]}
positionHistory: Array[1]
0: Object
estimatedSpeed: "39"
isToday: false
lastSoundFileName: "F11"
lastSoundRange: "11"
lastSoundTime: "2008-10-29 20:38:25"
lat: "51.466227"
long: "-0.491647"
minutesAgo: 1016726
status: "1"
time: "2011-07-13 16:03:37"
__proto__: Object
length: 1
__proto__: Array[0]
unitID: "03_Cow_30"
__proto__: Object
Ah, so your model attributes data structure is not what everyone thought. Based on your attributes structure, you need something like this. It's a bit fragile due to assuming positionHistory is an array with at least one element, but that's where your data is.
var ccLocal = window.router.carsCollection;
_.each(ccLocal.models, function(model) {
console.log(model.get('positionHistory')[0].lat);
})

Resources