FROM CACHE - en_header

Apollo and Graphql Help: "Could not find "client" in the context or passed in as an option."

DevBijan
Shopify Partner
27 0 9

Hi everyone, I have been trying to learn Graphql and I keep running into this error

"Invariant Violation: 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."

 

As of right now, my goal is to paginate through all the products of a store and add them to an array.

 

Code for ProductLoader:

 

import React, {useState, useContext} from 'react'
import {
    ApolloClient,
    InMemoryCache,
    ApolloProvider,
    useQuery,
    gql,
    NetworkStatus
  } from "@apollo/client";


export default function ProductLoader() {
 
    const [allProducts, setAllProducts] = useState([])
    const [cursor, setCursor] = useState("")
    const GET_STORE_PRODUCTS  = gql`
        query getProducts($cursor: String){
            products(first: 5, after: $cursor){
                pageInfo{
                    hasNextPage
                    hasPreviousPage
                }
                edges{
                    cursor
                    node{
                        title
                        handle
                        descriptionHtml
                        id
                        tags


                        images(first: 1) {
                            edges {
                                node {
                                    originalSrc
                                    altText
                                }
                            }
                        }
        
                        variants(first: 1) {
                            edges {
                                node {
                                price
                                id
                                }
                            }
                        }

                }
    
            }
        }

    }
  `;


  function apollo({cursor}){
    const { loading, error, data, refetch, networkStatus } = useQuery(
        GET_STORE_PRODUCTS,
        {
          variables: { cursor },
          notifyOnNetworkStatusChange: true,
        },
      );

    if (networkStatus === NetworkStatus.refetch) return 'Refetching!';
    if (loading) return <div>Loading...</div>
    if (error) return <div>{error.message}</div>

    return ( 
        setAllProducts([...allProducts], data.products.edges),
        setCursor(allProducts[allProducts.length-1].cursor)               
      );
  }
    return (
        apollo(cursor)
    )
}

 

 

 

Code for _app:

 

import { ApolloProvider } from "react-apollo";
import {  ApolloClient,  InMemoryCache,  createHttpLink,} from '@apollo/client';
import App from "next/app";
import { AppProvider } from "@shopify/polaris";
import { Provider, useAppBridge } from "@shopify/app-bridge-react";
import { authenticatedFetch } from "@shopify/app-bridge-utils";
import { Redirect } from "@shopify/app-bridge/actions";
import "@shopify/polaris/dist/styles.css";
import translations from "@shopify/polaris/locales/en.json";
import React, {useContext} from 'react';






export const ApolloClientContext = React.createContext()

function userLoggedInFetch(app) {
  const fetchFunction = authenticatedFetch(app);

  return async (uri, options) => {
    const response = await fetchFunction(uri, options);

    if (
      response.headers.get("X-Shopify-API-Request-Failure-Reauthorize") === "1"
    ) {
      const authUrlHeader = response.headers.get(
        "X-Shopify-API-Request-Failure-Reauthorize-Url"
      );

      const redirect = Redirect.create(app);
      redirect.dispatch(Redirect.Action.APP, authUrlHeader || `/auth`);
      return null;
    }

    return response;
  };
}

function MyProvider(props) {
  const app = useAppBridge();

  const client = new ApolloClient({
    fetch: userLoggedInFetch(app),
    fetchOptions: {
      credentials: "include",
    },
    link: new createHttpLink({
      credentials: 'include',
      headers: {
        'Content-Type': 'application/graphql',
      },
    }),
    cache: new InMemoryCache(),
  });
  const Component = props.Component;

  return (
    <ApolloProvider client={client}>
      <Component {...props} />
    </ApolloProvider>
  );
}

class MyApp extends App {
  render() {
    
    const { Component, pageProps, host } = this.props;
    return (
        <AppProvider i18n={translations}>
          <Provider
            config={{
              apiKey: API_KEY,
              host: host,
              forceRedirect: true,
            }}
          >
            <MyProvider Component={Component} {...pageProps} />
          </Provider>
        </AppProvider>
        
    );
  }
}

MyApp.getInitialProps = async ({ ctx }) => {
  return {
    host: ctx.query.host,
  };
};

export default MyApp;

 

The _app file was created by the ShopifyCLI so I'm not sure if anything in there is causing the problem as there is an ApolloProvider passed through. 

 

code for index:

import { Heading, Page } from "@shopify/polaris";
import ProductLoader from "./components/ProductLoader";

const Index = () => ( 
  <Page>
    <ProductLoader />
  </Page>
);

export default Index;

 

I'm not sure where to try and fix this problem so any help would be appreciated, thanks!

Replies 5 (5)
Brandammo
Shopify Partner
5 0 2

@DevBijan Did you find a solution to this? I'm having the same issue.

 

Any help would be greatly appreciated.

rbmdotdev
Tourist
5 0 1

I am also having the same issue with the app set up the documented way and everything wrapped in ApolloClient but child components not being able to find the client

DevBijan
Shopify Partner
27 0 9

Hi all, I didn't find a specific solution to this, but I did find that some of my imports were causing issues. Once I fixed that it started to work.

FrankLi
Tourist
11 2 1

I also find this problem, but its slightly different. It might be helpful if you check you ApolloProvide and ApolloClient are from same package. As the react-apollo might be deprecated. From your code, the ApolloProvider from react-apollo, but the ApolloClient is from apollo/client.  The project that created by shopify-cli use old version of react-apollo. We'd better migrate it to new supported version.

ayoub11
New Member
1 0 0