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
Related
i have a document in firestore like below
what i want to do is update this fields time and stage
i tried these with update and set methods
db.collection("record").doc("user"+user).collection("datas").doc("roadmap").update({
first:[{
0:[ stage:"new stage",
time:"new time,
done:false
}]
}]
})
and
db.collection("startups").doc("user"+user).collection("datas").doc("roadmap").update({
first:{[
stage:"new stage",
time:"new time",
done:false
}]
})
but it always shows error such as :[![FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: undefined]
The following should do the trick:
db.collection("record").doc("user"+user).collection("datas").doc("roadmap")
.update({ first: [{ stage: 'new stage', time: 'new time', done: false }] });
This will work because your array has only one element (a map).
Note that if you want to modify one specific element of an array with several elements, you will need to first read the array in your front-end, modify the array and then write back the modified array to Firestore.
Even if it is not what you are looking for, it's worth noting the arrayUnion() and arrayRemove() methods, see here for more details.
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();
I'm experiencing little trouble getting Orionjs working within Angular-Meteor especially with the collections.
I had my old mongodb declarations, for instance :
Gallery = new Mongo.Collection('gallery') and so one.
As the documentation told , I wrote
Gallery = new orion.collection('gallery') but what I get is
Error: Match error: Expected object, got undefined
at exports.check (packages/check/match.js:34:1)
at new orion.collection (packages/orionjs:collections/new.js:8:3)
at meteorInstall.shared.collections.js (shared/collections.js:1:11)
So I tried to start a project from scratch with this framework.
Fact is, it doesn't work neither with Iron Router nor Flow Router.
Can anyone hit me with any hint about it?
Thank you guys.
Ideally OrionJS expect a schema detail like the label for singular and plural names, navigation detail, table layout for displaying data and so on.Here's a typical company collection shown below:
Company = new orion.collection('company', {
singularName: orion.helpers.getTranslation('company.singularName'),
pluralName: orion.helpers.getTranslation('company.pluralName'),
title: orion.helpers.getTranslation('company.title'),
link: {
title: orion.helpers.getTranslation('company.title'),
parent: 'collections-abc'
},
tabular: {
columns: [
{ data: '_id', title: orion.helpers.getTranslation('company.schema.id') },
{ data: 'name', title: orion.helpers.getTranslation('company.schema.name') }
]
}
});
You can also pass a null JSON if you do not wish to show page directly. Usually it expects a JSON like the one shown above.
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()
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);
})