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()
Related
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
I am having trouble to have a map within a map.
As you can see below I have commented several tries, ideally I wanted to use workItem.bullets.map((bulletItem, i)=><li key={i}>{bulletItem}</li>)
directly.
If I use it directly I will have "Cannot read properties of undefined (reading 'map')".
On this version I will get a undefined is not iterable (cannot read property Symbol(Symbol.iterator)) even though console.log seems to work fine and shows the type as Array as expected. The Array.from is useless but I since I am not understanding what's happening I gave it a try.
const work = this.props.data.work.map( workItem => {
console.log(workItem.bullets);
//let bulletPts = workItem.bullets.map((bulletItem, i)=><li key={i}>{bulletItem}</li>);
//let bps = workItem.bullets.map((bulletItem, i)=>"toto");
let array = Array.from(workItem.bullets);
return (
<div key={workItem.company}>
<h3>{workItem.company}</h3>
<p className="info">
{workItem.title}
<span>•</span> <em className="date">{workItem.years}</em>
</p>
<p>{workItem.description}</p>
<ul>
{
array.map(bulletItem => "test")
}
</ul>
</div>
);
});
I also took a look at How to map inside a map function in reactjs as it looked like a similar problem but I was not able to apply it to my issue.
I don't think it is needed but If you want to see the full project I am trying to add bullet points for resume, resumeData.json needs to be modified to contain some bulletPoints.
https://github.com/nordicgiant2/react-nice-resume
There is somethign wrong with your JSON :D
I'm pulling in data from an API and trying to display it on my bootstrap table. It displays but I'm getting some errors. The first issue is in regard to 'data' being required.
The second issue seems to be the data hasn't loaded in time but I've used an if statement to load the data first.
if (this.props.dataState.loaded){
data = this.props.data.content;
} else {
this.renderLoading();
}
return( ...
Sometimes it displays the page without issues, other times it effects the other components and they won't load. I always get the console errors.
Any idea what I'm doing wrong?
Thanks!
You need to check the existence of dataState too, the same way you are checking for dataState.loaded. For the below code, I am assuming the default Props type for data.content is an array.
Try this:
if (this.props.dataState && this.props.dataState.loaded){
data = this.props.data.content ? this.props.data.content : [] ;
} else {
this.renderLoading();
}
I hope this will work.
im looping through data
This is react.js / jsx
If I am pulling 100 items, none will show because of one being undefined. I just want it to display "0" if it is undefined, and show the size if it is there.
Error: Cannot read property size of undefined.
Example of data,
Item={
color:blue,
size:medium,
}
Item={
color:red
}
I am mapping through the data.
Im essentially doing this :
return items.map((item, i) => {
return( {item.size})
I have also tried {item.size ? "itWorks" : "0"} as a test, and I get the same error.
It is better to use object.hasOwnProperty('property') to check whether your object has a particular property or not . for your case it is:
{item.hasOwnProperty('size') ? "itWorks" : "0"}
The error is:
Error: Cannot read property size of undefined
It means item is undefined,
So you gotta check for item and item.size.
You should do,
return (
items && items.map(function(item, id){
.....}))
So the loop goes through when items array is of some length otherwise it exits
I have a collection named People that holds multiple documents. I am using Meteor JS for my website. When I run People.find({status: "Pending"}) it initially returns an empty array. If I wrap it in a Tracker.autorun:
Tracker.autorun(function(){
var peeps = People.find({status: "Pending"})
Session.set('listo', peeps)
console.log(peeps)
})
It finds the documents after first returning an empty array.
// => []
// => [{}]
The issue is that the first value (the empty array) is getting passed to my template and it is displaying none of the documents. I am using react for rendering:
render() {
return (
{
Session.get('listo').map((item) => {
HTML HERE
})
)
}
I thought that a session variable would work for this case but maybe this is conflicting with react or something, I'm not really sure.
To clarify the problem, the data always eventually gets loaded into the the listo session variable but this new data is not displayed in the render() function.