Can't load in images from Contentful using GatsbyJS - reactjs

First time posting here, but I've been struggling with this for a few days now.
Basically I have a graphQL query that pulls in product data from contentful and then display it on a GatsbyJS page. The query correctly displays for the title, price, and description of the product but it wont load in the image. Unfortunately I keep receiving errors such as:
"TypeError: Cannot read property '0' of undefined"
or
Cannot read property 'src' of undefined. (When changing the query to look at the src of an image. When I do this method, the url does have a value according to GraphiQL)
here's the code for the page I am currently working on:
import React from 'react'
import { graphql } from 'gatsby'
import Img from 'gatsby-image'
import Layout from '../components/Layout'
import './shop.scss'
const Shop = ({ data }) => {
return (
<Layout>
<section>
{data.allContentfulProducts.edges.map( ({ node }) => (
<article key={node.id}>
<Img
fluid={node.images.fluid}
/>
<p>{node.productName}</p>
</article>
))}
</section>
</Layout>
)
}
export const productQuery = graphql`
query {
allContentfulProducts {
edges {
node {
id
productName
images {
fluid {
...GatsbyContentfulFluid
}
}
}
}
}
}
`
export default Shop

I think there is a problem with you graphQL Query. Try this one:
export const productQuery = graphql`
query {
allContentfulProducts {
edges {
node {
id
productName
image {
fluid {
src
...GatsbyContentfulFluid
}
}
}
}
}
}
`
If this query is not helping please show us the structure of your contentful assets.

Related

GraghQL query returning integer instead of object

I can't figure out why none of my queries are working on my Gatsby projects.
import React from "react"
import { graphql } from "gatsby"
const site_info = () => {
const query = graphql`
query title {
allSite {
edges {
node {
siteMetadata {
title
}
}
}
}
}
`
console.log(query)
return <p>Test</p>
}
export default site_info
In the console, I'm expecting an object where I can see the title in metadata, however, I'm getting 2641826822.
I copied the query directly from GraphiQL where I'm seeing the expected result, so not sure why it isn't working here.
When you query (using a page query as you've provided) some data using GraphQL in a Gatsby schema, your data is stored as a page prop (not in the query variable itself), so you need to access to them props and iterate through the object until you find your data. An ideal structure data should look something like:
const yourPage = ({ data }) => {
const { title } = data.allSite.edges[0].node.siteMetadata;
return <Layout>
<h1>{title}</h1>
</Layout>;
};
export const yourPageData = graphql`
query title {
allSite {
edges {
node {
siteMetadata {
title
}
}
}
}
}
`;
export default yourPage;
Basically, in the snippet above I'm destructuring data as a prop (instead of doing prop.data) and I do the same with data.allSite.edges[0].node.siteMetadata to get the title.
I would recommend some documentation reading about Querying Data in Pages with GraphQL before you dive into GraphQL on the rocks.

Gatsby / Graphql - Can't display img from query

Below is my code:
import React from 'react'
import { graphql, useStaticQuery } from "gatsby"
import Img from 'gatsby-image'
const ImageGallery = () => {
const data = useStaticQuery(graphql`
query {
images: allFile(filter: { sourceInstanceName: {eq: "images" }}) {
edges {
node {
relativePath
childImageSharp {
id
fluid {
originalImg
}
}
}
}
}
}
`)
// Filters all the images from "gallery-one"
const galleryImages = data.images.edges.filter(edge =>
edge.node.relativePath.startsWith("gallery-one")
)
console.log(data)
console.log(galleryImages)
return (
<div>
<h1>Gallery One</h1>
{
// Mapping over galleryImages array to display each image
galleryImages.map((image) =>
<div>
// Returns relative path for each image
{image.node.childImageSharp.fluid.originalImg}
// Returns nothing
<Img fluid={image.node.childImageSharp.fluid.originalImg} />
</div>
)
}
</div>
)
}
export default ImageGallery
With the first part in the map, it returns:
/static/3608211e3ce3f78486c9e344b92332d9/5f7bf/20171107_155145.jpg
/static/fccd9cdb1c9b525bfaf9282343d680a6/5f7bf/20171101_103124.jpg
/static/cdcbaebc030e210debc70bdff7a8d539/5f7bf/20171107_155126.jpg
/static/ef8708d7f536bd152c9ce98833d6d871/5f7bf/20171101_103218.jpg
/static/1c3b4e40cb5044e604009935b625fa38/5f7bf/20171101_103138.jpg
One for each image in the 'gallery-one' folder, but I cannot figure out how to get it to display using Gatsby Img.
I feel like this is really close, but I can't seem to figure it out
fluid={image.node.childImageSharp.fluid.originalImg}
Yes, you're almost there.
When you query an image to be displayed using gatsby-image you have 2 options:
Use a GraphQL fragment:
Instead of using originalImg you should use ...GatsbyImageSharpFluid which will provide to the fluid object all information required.
Querying all the data required. In this case you should use:
fluid (maxWidth: 800) {
aspectRatio
src
srcSet
sizes
originalImg
originalName
}
Disclaimer: the default maxWidth is 800px. If you don't set it, it will take the default value.
Once you gathered all the information, it needs to be passed to <Img> removing your originalImg, such as:
fluid={image.node.childImageSharp.fluid}
For further information check Gatsby Image API documentation.

GraphQL query displays only raw results

I have a GraphQL query kind of working (React, Gatsby, Typescript). But I only get browser to display raw json data (the "stringify" thing is what's correctly visible, raw json).
Whenever I try to use data bindings, I get error message "TypeError: undefined is not an object (evaluating 'ProjectTitles.edges.node')" in the browser. But not in console. What could be wrong? Here's the code:
import { graphql, useStaticQuery } from "gatsby";
import React, { Fragment } from "react";
const ProjectList = () => {
const ProjectTitles = useStaticQuery(graphql`
{
allMarkdownRemark(sort: { fields: frontmatter___title }) {
edges {
node {
frontmatter {
title
}
}
}
}
}
`);
return (
<Fragment>
<h2>Project titles</h2>
<div>{ProjectTitles.edges.node.frontmatter.title}</div>
{/* <div>{ProjectTitles.allMarkdownRemark.edges.node.frontmatter.title}</div> */}
{/* <div>{ProjectTitles}</div> */}
<pre>{JSON.stringify(ProjectTitles, null, 2)}</pre>
</Fragment>
);
};
export default ProjectList;
Since edges will most likely be an array you need to access a certain item or map the whole array, e.g.
{ProjectTitles.edges.map(node => (
<div>{node.frontmatter.title}</div>
))}

Trying to Display Additional Image Thumbnails Below Main Featured Product Image

Can't get files from Moltin API to display under main product image
Using this repo: https://github.com/moltin/gatsby-demo-store and updating
#moltin/gatsby-source-moltin to 1.3.1 I have tried expanding the product
node schema to include relationships as per Moltin API documentation then
referencing this in a new component but no additional images render.
Had a look at other implementations i.e. Gatsby Store example which uses
Thumbnails and could get a tiny clickable thin purple strip rendering but with no image. The store uses Shopify and localFile storage for image rendering so this use case is not applicable.
```
import React, { useContext, useEffect, useReducer, useState } from 'react'
import { graphql, withPrefix } from 'gatsby'
import SEO from '../components/SEO'
import Photo from '../components/Photo'
import Badge from '../components/Badge'
import AddToCart from '../components/AddToCart'
import { Shopkit } from '../shopkit'
import Img from 'gatsby-image'
const {
meta: { display_price }
} = product
return (
<React.Fragment>
<SEO
type="product"
title={product.meta_title || product.name}
description={product.meta_description || product.description}
image={withPrefix(product.mainImage.childImageSharp.fixed.src)}
/>
<div className="flex flex-wrap md:bg-grey-light">
<div className="py-2 md:py-5 md:px-5 w-full lg:w-1/2">
<div className="sticky pin-t">
<Photo
src={product.mainImage}
alt={product.main_image_alt_text || product.name}
/>
<Img
src={product.relationships.files.data.id}
alt=""
/>
</div>
</div>
......
.....
....
</React.Fragment>
)
}
export const query = graphql`
query($id: String!) {
product: moltinProduct(id: { eq: $id }) {
id
slug
name
description
sku
mainImage {
childImageSharp {
fixed(width: 560) {
...GatsbyImageSharpFixed
}
}
publicURL
}
meta {
display_price {
without_tax {
formatted
}
}
}
manage_stock
meta_title
meta_description
on_sale
bulb
bulb_qty
material
finish
max_watt
relationships {
main_image {
data {
id
}
}
files {
data {
type
id
}
}
}
`
export default ProductPage
```
Would like to get small thumbnail rending below main product image. Console
error message when using Img component: Uncaught TypeError: Cannot read
property 'src' of undefined.
gatsby-source-moltin adds a images field to the product schema which you can query like so:
images {
childImageSharp {
fluid(maxWidth: 300) {
...GatsbyImageSharpFluid
}
}
}
I put together an example on CodeSandbox.

Stuck on GraphQl query in Gatsby using imageSharp

I am trying to get the following background prop set to a image in my src/images/bird.jpg directory. Here is my code, but I get a Cannot read property 'id' of undefined from my graphQl query in the console and the background prop returns null in React Inspector, What am I doing wrong?
/src/pages/index.js
import React from 'react'
import { graphql } from 'gatsby'
import Img from 'gatsby-image'
import Layout from '../components/layout'
const IndexPage = ({ data }) => (
<Layout>
<h1>Hi people</h1>
<p>{data.site.siteMetadata.title}</p>
<p>{data.site.siteMetadata.desc}</p>
<p>Welcome to your new Gatsby site.</p>
<p>Now go build something great.</p>
</Layout>
)
export default IndexPage
export const query = graphql`
query SiteMeta {
site {
siteMetadata {
title
desc
}
}
background: imageSharp(id: { regex: "/bird.jpg/" }) {
sizes(maxWidth: 1240) {
...GatsbyImageSharpSizes
}
}
}
`

Resources