On Gatsby, how to do a GraphQL query using a prop? - reactjs

I'm passing a prop to a new component and trying to use that to do a graphql query. It looks like this.
import React from "react"
import { graphql, useStaticQuery } from "gatsby"
import Img from "gatsby-image"
const ComponentName = props => {
const getImage = graphql`
{
image: file(relativePath: { eq: ${props.img} }) {
childImageSharp {
fluid {
...GatsbyImageSharpFluid
}
}
}
}
`
const data = useStaticQuery(getImage)
return (
<li>
<Img
fluid={data.image.childImageSharp.fluid}
/>
</li>
)
}
export default ComponentName
But I'm getting this error BabelPluginRemoveGraphQLQueries: String interpolations are not allowed in graphql fragments. Included fragments should be referenced as...MyModule_foo.
I've tried all sorts of different tricks to get rid of the "string interpolation" error. But none of them work (it just shows a different error each time).
I'm assuming you can't do a graphql query using props? Or is there another way to do this?

From StaticQuery docs:
StaticQuery does not accept variables (hence the name “static”), but can be used in any component, including pages.
And same for the hook version useStaticQuery:
useStaticQuery does not accept variables (hence the name “static”), but can be used in any component, including pages.
You can read further in gatsby's GitHub here.

Related

How can I dynamically add images to my pages in Gatsby using the image component?

So I have the image component that renders 2 different images, but I want to be able to just add my image component to any page and just pass in the specific image as a prop instead of having to hard code a new query for each image I need to use.
If I had 50 images, I'd like to just pass image-50.jpg in as a prop instead of making a specific query for it. Is there a way to do that with graphql in gatsby?
Here is my current image component code
import { graphql, useStaticQuery } from "gatsby"
import Img from "gatsby-image"
import React from "react"
const Image = () => {
const data = useStaticQuery(graphql`
query {
astronaut: file(relativePath: { eq: "gatsby-astronaut.png" }) {
childImageSharp {
fluid(maxHeight: 600) {
...GatsbyImageSharpFluid
}
}
}
person: file(relativePath: { eq: "profile.jpg" }) {
childImageSharp {
fluid(maxHeight: 600) {
...GatsbyImageSharpFluid
}
}
}
}
`)
return (
<>
<Img fluid={data.astronaut.childImageSharp.fluid} />
<Img fluid={data.person.childImageSharp.fluid} />
</>
)
}
export default Image
Is there a way to just add the image dynamically and then render it to a new page?
Something like this <Image src={"profile.jpg"} />
I don't know how I could add that to the graphql and imagine I have 50 images, then I would have to either map through all 50 or manually add each query and that doesn't make sense
Believe it or not you cannot create a fully dynamic image component using a gastby-image without risking a (possibly very large) bloat in your bundle size. The problem is that static queries in Gatsby do not support string interpolation in it's template literal. You would need to search through all the files each time you use the component.
There are some solutions you can try in an existing SO post found here.
You can always use graphql fragments and write something like the below for your queries and then conditionally render the proper image based on a file name passed via props in your Image component but alas this also pretty clunky:
export const fluidImage = graphql`
fragment fluidImage on File {
childImageSharp {
fluid(maxWidth: 1000) {
...GatsbyImageSharpFluid
}
}
}
`;
export const data = graphql`
query {
imageOne: file(relativePath: { eq: "one.jpg" }) {
...fluidImage
}
imageTwo: file(relativePath: { eq: "two.jpg" }) {
...fluidImage
}
imageThree: file(relativePath: { eq: "three.jpg" }) {
...fluidImage
}
}
`
// accessed like this
<Img fluid={data.imageOne.childImageSharp.fluid} />
// or this
<Img fluid={data.imageTwo.childImageSharp.fluid} />
// or this, dynamically (if you had a prop called imageName)
<Img fluid={data.[`${props.imageName}`].childImageSharp.fluid} />
As Apena's answer explains, it's tricky to work like that with Gatsby's Image. However, I must say that you can bypass it in different ways depending on the filesystem used and how the data is structured.
Keep in mind that if you set properly the filesystem in your gatsby-config.js, you are allowing Gatsby to recognize and to find all your images in your project, making them queryable and allowing them to be used by Gatsby Image component.
const path = require(`path`)
module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: path.join(__dirname, `src`, `images`),
},
},
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
],
}
You can find much better ways than querying each image in a staticQuery filtered by the path, it's not true that is the only way to achieve it. Of course, if you are using a staticQuery approach, the limitation of making it dynamic forces you to make each query separately.
First of all, you need to know the difference between staticQuery and page query to understand which fits you and the limitations of them.
If you use a page query, you can always create an approach like the following one:
import React from 'react'
import { graphql } from 'gatsby'
import Layout from '../components/layout'
class ProductPage extends React.Component {
render() {
const products = get(this, 'props.data.allDataJson.edges')
return (
<Layout>
{products.map(({ node }) => {
return (
<div key={node.name}>
<p>{node.name}</p>
<Img fluid={node.image.childImageSharp.fluid} />
</div>
)
})}
</Layout>
)
}
}
export default ProductPage
export const productsQuery = graphql`
query {
allDataJson {
edges {
node {
slug
name
image{
publicURL
childImageSharp{
fluid {
...GatsbyImageSharpFluid
}
}
}
}
}
}
}
`
In the example above, you are using a page query to retrieve all images from a JSON file. If you set the path in your filesystem, you will be able to retrieve them using the GraphQL fragments. This approach is the more dynamic you can afford when dealing with Gatsby Image and it's better to query one by one.
The idea remains the same for other filesystems, this is just an adaptable approach. If you are using a CMS like Contentful, you can download the assets and query them dynamically in the same way since the filesystem allows you to do it.
Pages queries are only allowed in page components (hence the name) so, if you want to use it in a React standalone component to make it reusable, you will need to pass via props (or reducer) to your desired component and render the Gatsby image based on the received props.

Reusable Gatsby Transformer Cloudinary Image dynamic image sources

I've installed "gatsby-transformer-cloudinary" to my gatsby website. I've implemented API integration and It can be fetched and I can see any single image on a page from Cloudinary. I just want to use this component dynamically and I need your help how do I used image name area as dynamically like props ((eg: "image"))?
import React from "react"
import { graphql, useStaticQuery } from "gatsby"
import Image from "gatsby-image"
export default (props) => {
const data = useStaticQuery(graphql`
query {
image: file(name: { eq: "3144_xl-2015" }) {
cloudinary: childCloudinaryAsset {
fixed(width: 300) {
...CloudinaryAssetFixed
}
}
}
}
`)
return (
<div className="image-example">
<Image
fixed={data.image.cloudinary.fixed}
alt={props.alt}
title={props.title}
/>
</div>
)
}
You are using a staticQuery (or useStaticQuery hook, in the end it works exactly in the same way), since it's a limitation from it, you can't pass variables. From the documentation:
StaticQuery does not accept variables (hence the name “static”), but
can be used in any component, including pages
If you want to use a dynamic <Img> component from gatsby-image you will need to use a page query and pass some kind of unique value (like a slug) and filter through it.

Storybook Mock GraphQL (Gatsby)

I am using Gatsby to create a blog. Gatsby can use markdown with GraphQL to "automagically" create post pages for you. I was wondering using the Gatsby example here.
In storybook UI what is the best way to "mock" out the graphql query and replace it with our markdown data. So that I can test this component in Storybook UI. For example if I have a blog template that looks something like:
import { graphql } from 'gatsby';
import React from 'react';
export default function Template({
data, // this prop will be injected by the GraphQL query below.
}) {
const { markdownRemark } = data; // data.markdownRemark holds your post data
const { frontmatter, html } = markdownRemark;
return (
<div className="blog-post-container">
<div className="blog-post">
<h1>{frontmatter.title}</h1>
<h2>{frontmatter.date}</h2>
<div
className="blog-post-content"
dangerouslySetInnerHTML={{ __html: html }}
/>
</div>
</div>
);
}
export const pageQuery = graphql`
query($slug: String!) {
markdownRemark(frontmatter: { slug: { eq: $slug } }) {
html
frontmatter {
date(formatString: "MMMM DD, YYYY")
slug
title
}
}
}
`;
Thanks in advance
You can probably modify the webpack configuration of Storybook to use the NormalModuleReplacementPlugin to mock the whole gatsby package. Then export a graphql method from your mock that you can manipulate in your stories.
Alternatively, split your component into a pure component and a component that performs the query and just use the pure component as suggested in https://www.gatsbyjs.org/docs/unit-testing/

How to use GraphQL mutation in Next.js without useMutation

I'm working on a codebase with Next.js version 9.3.0 and GraphQL. To get the benefits of Next.js optimizations, we are wrapping each page in withApollo, so inside the pages we can make use of useQuery, useMutation.
The issue I'm facing is that I need to use mutation in the Header component which is outside the page, which doesn't have access to ApolloClient because the app is not wrapped in withApollo.
The error I'm getting is this Could not find "client" in the context or passed in as an option. Wrap the root component in an <ApolloProvider>, or pass an ApolloClient instance in via options.
The Header component is inside the Layout component like this:
<>
<Meta />
<Header/>
{children} // pages which are composed with withApollo
<Footer />
</>
Instead of using useQuery in a component without withApollo is easy you can use
import { createApolloFetch } from 'apollo-fetch';
const fetch = createApolloFetch({
uri: process.env.GRAPHQL_SERVER,
});
const userInfoQuery = `{
userInfo {
loggedIn
basketCount
wishListCount
}
}`;
const userInfoData = fetch({
query: userInfoQuery,
});
Is there an alternative solution for useMutation in a component not composed with withApollo?
Any suggestions are welcomed,
Cheers
Silly me, mutations work with Apollo fetch too
https://github.com/apollographql/apollo-fetch#simple-graphql-mutation-with-variables but this is not maintained anymore
The solution that worked for me, in the end, was to still useMutation and to pass the client to it.
https://www.apollographql.com/docs/react/data/mutations/#usemutation-api
import { useMutation } from '#apollo/react-hooks';
import createApolloClient from 'lib/apolloClient';
import loginUser from 'mutations/login';
const [getToken, { data: mutationData, error: loginErrors, loading }] = useMutation(loginUser, { client: createApolloClient()});

How do you get URL parameters from react-router outside components to use in GraphQL query

Is it possible to access the URL params supplied in a route outside the components?
This of course can be accomplished with window.location but I am looking for something in the react-router API to do this more cleanly.
Additionally, if there is a more standard approach to doing this with GraphQL, that's even better! I am just looking into browser clients for gql and new to gql in general.
Example component:
import React from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import get from 'lodash.get';
const ContractComponent = (props) => {
...
};
const ContractQuery = gql`query ContractQuery ($contractId: String!){
contract(id: $contractId) {
...
}
}`;
const ContractWithData = graphql(ContractQuery, {
options: { variables: { contractId: contractId } }, // <-- var i want to pull from url params
})(ContractComponent);
export default ContractWithData;
Example route:
<Route path="contract/:contractId" component={Contract} />
I'm not really familiar with react-apollo, but I think the following is a good way to achieve what you want.
You can see in the docs that options can be a function taking the component props as input, returning an object with the options: http://dev.apollodata.com/react/queries.html#graphql-options
So I think you can do:
const ContractWithData = graphql(ContractQuery, {
options: props => ({ variables: { contractId: props.params.contractId } })
})(ContractComponent);
In the code above, props.params are the params passed by react-router to the route component (nothing special there).
You want to write options as a function when you need do to something dynamic at runtime, in this case accessing the route params.
Hope it helps.

Resources