Make graphql query outside a JSX component in Gatsby

纵饮孤独 提交于 2020-06-29 04:30:28

问题


I have a .ts(not .tsx) file which just exports a json object like

const obj = {
    img1: gql_img1,
    img2: gql_img2
}

I want gq1_img1 and gq1_img2 to be the results of a graphql query

I found a solution which uses Apollo Client, but it doesn't look like they're using Gatsby and I don't think Gatsby uses a client.

The problem with using useStaticQuery is that it's a hook, if I try to use it like in the snippet below, I get "Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:"

const gql = () => {
    
    const gql = useStaticQuery(graphql
        `query adQuery {
            invoiceNinja300x250: file(
                extension: {regex: "/(jpg)|(jpeg)|(png)/"},
                name: {eq: "IN-300x250-2"}
            ){
                childImageSharp {
                    fluid(maxWidth: 250) {
                        ...GatsbyImageSharpFluid_withWebp_noBase64
                    }
                }
            },
            invoiceNinja600x300: file(
                extension: {regex: "/(jpg)|(jpeg)|(png)/"},
                name: {eq: "IN-600x300-2"}
            ){
                childImageSharp {
                    fluid(maxWidth: 250) {
                        ...GatsbyImageSharpFluid_withWebp_noBase64
                    }
                }
            }
        }`
        
        )
    return gql
}

    const GQL = gql() 

回答1:


Like I mentioned in your reddit post, if you're not using a page query or static query, you'll need Apollo Client or some other gql client.

I found a solution which uses Apollo Client, but it doesn't look like they're using Gatsby and I don't think Gatsby uses a client.

Gatsby and GraphQL clients are different things. Gatsby is a React framework for building static websites and uses graphQL to fetch data in various ways. A GraphQL client is much like fetch or axios, they are libraries used to request, post, update, delete data from a REST API.

Can you explain your use case a bit? Maybe there is a more Gatsby way of doing it.




回答2:


Have you considered the React Context API? On the production Gatsby app I work on that's what we use for global variables like some JSON/object data. It allows you in some sort of high level/layout/data layer component to stuff some values you get from a different file into your app to use with other components.



来源:https://stackoverflow.com/questions/62502019/make-graphql-query-outside-a-jsx-component-in-gatsby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!