Example of the Gatsby/Contentful Starter Code:
import get from 'lodash/get'
...
const post = get(this.props, 'data.contentfulBlogPost')
const siteTitle = get(this.props, 'data.site.siteMetadata.title')
Why are they using lodash 'get' instead of directly refering to the graphql-query result 'data' in the html code?
By using 'get' from lodash, which can handle some cases that this.props.data
is undefined
, to avoid the code throwing some error if you try to access this.props.data.contentfulBlogPost
.
You can also using this.props?.data?.contentfulBlogPost