Open marcuslindfeldt opened 5 years ago
Hey @marcuslindfeldt
StaticQuery
would have been an optimal solution, unfortunately, it doesn't support variables.
But you could do the following by querying allContentfulAsset
and later filtering by id.
import React from "react"
import { graphql, useStaticQuery } from "gatsby"
import Image from "gatsby-image"
// Gatsby adds 'c' to entity id if it starts with a number.
function fixId(id) {
if (id.length === 23 && id.startsWith("c")) {
return id.slice(1)
}
}
export const ContentfulFixedAsset = ({ contentfulId }) => {
const data = useStaticQuery(graphql`
query {
allContentfulAsset {
edges {
node {
contentful_id
fixed {
base64
tracedSVG
aspectRatio
width
height
src
srcSet
srcWebp
srcSetWebp
}
}
}
}
}
`)
const image = data.allContentfulAsset.edges.find(
edge => edge.node.contentful_id === fixId(contentfulId)
)
return <Image fixed={image.node.fixed} />
}
export default ContentfulFixedAsset
@sbezludny This would probably work but this solution will query all assets on contentful right for in my case every blog post that gatsby builds? Is it not possible to query only the assets related to the rich text field or the content model?
this solution will query all assets on contentful right for in my case every blog post that gatsby builds?
No additional api calls will be made. AFAIK, Gatsby uses sync API under the hood, which means that all the assets are already available on the client side all the time.
Is it not possible to query only the assets related to the rich text field or the content model?
No, querying to the rich text is not possible at the moment.
I'm unable to use gatsby-image in combination with Contentful rich text queried via gatsby-source-contentful because the graphql schema for contentful that gatsby generates does not allow me to query an embedded asset in rich text as I would if I just query a single asset.
I created an issue in the gatsby repo (https://github.com/gatsbyjs/gatsby/issues/14338) describing this issue but maybe it's more appropriate here.