I'm trying to retrieve with lodash a record from a Firebase db as array of objects by using the url param which matches the slug
property. When I try to show the object properties (example the url
property) in the render method I get TypeError: Cannot read property 'url' of undefined
. If I console log this.props.match.params.slug
I get the right param though.
here's the object I get from Firebase:
{
"category" : "illustrations",
"medium" : "ink",
"slug" : "black-and-white",
"thumb" : "https://.....png",
"title" : "black and white",
"url" : "https://.....png"
}
Here's my component:
import React from 'react';
import _ from 'lodash';
import base from '../base';
class Painting extends React.Component {
constructor() {
super()
this.state = {
pictures: []
}
}
// firebase syncing
componentWillMount() {
this.ref = base.syncState('pictures', {
context: this,
state: 'pictures',
asArray: true
});
}
renderImage() {
if (!this.state.pictures) {
return ("Loading...");
} else {
return <p>{_.find(this.state.pictures, { slug: this.props.match.params.slug }).url}</p>
}
}
render() {
console.log(this.props.match.params.slug)
return(
<div>
{this.renderImage()}
</div>
)
}
}
export default Painting;
What am I doing wrong?
Because your pictures
is empty, and lodash find undefined.
Little fix your renderImage
method:
renderImage() {
if (!this.state.pictures || this.state.pictures.length === 0) {
return ("Loading...");
} else {
return <p>{_.find(this.state.pictures, { slug: this.props.match.params.slug }).url}</p>
}
}
So then, after fetching if you will have some items in pictures, this method will be render correctly.