@apollo/client#ApolloClient JavaScript Examples

The following examples show how to use @apollo/client#ApolloClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: client.js    From nextjs-boilerplate with MIT License 7 votes vote down vote up
client = () =>
  new ApolloClient({
    credentials: "include",
    link: ApolloLink.from([
      new HttpLink({
        uri: settings.graphql.uri,
        credentials: "include",
      }),
    ]),
    cache: new InMemoryCache(),
    defaultOptions: {
      watchQuery: {
        errorPolicy: "all",
        fetchPolicy: "network-only",
      },
      query: {
        errorPolicy: "all",
        fetchPolicy: "network-only",
      },
      mutate: {
        errorPolicy: "all",
      },
    },
  })
Example #2
Source File: dataProvider.js    From acy-dex-interface with MIT License 6 votes vote down vote up
export function useGraph(querySource, { subgraph = null, subgraphUrl = null, chainName = "arbitrum" } = {}) {
  const query = gql(querySource)

  if (!subgraphUrl) {
    if (!subgraph) {
      subgraph = getChainSubgraph(chainName)
    }
    subgraphUrl = `https://api.thegraph.com/subgraphs/name/${subgraph}`;
  }

  const client = new ApolloClient({
    link: new HttpLink({ uri: subgraphUrl, fetch }),
    cache: new InMemoryCache()
  })
  const [data, setData] = useState()
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  useEffect(() => {
    setLoading(true)
  }, [querySource, setLoading])

  useEffect(() => {
    client.query({query}).then(res => {
      setData(res.data)
      setLoading(false)
    }).catch(ex => {
      console.warn('Subgraph request failed error: %s subgraphUrl: %s', ex.message, subgraphUrl)
      setError(ex)
      setLoading(false)
    })
  }, [querySource, setData, setError, setLoading])

  return [data, loading, error]
}
Example #3
Source File: client.js    From gatsby-apollo-wpgraphql-jwt-starter with MIT License 6 votes vote down vote up
client = new ApolloClient({
  link: from([
    authMiddleware,
    onErrorLink,
    refreshTokenLink,
    httpLink
  ]),
  cache: new InMemoryCache({ possibleTypes }),
})
Example #4
Source File: app.js    From x-admin-device-donation with MIT License 6 votes vote down vote up
App = () => {
  const [dataProvider, setDataProvider] = useState(null);
  const [apolloClient, setApolloClient] = useState(null);
  const [session] = useSession();

  useEffect(() => {
    const hasuraHeaders = {};
    hasuraHeaders.Authorization = `Bearer ${session.jwt}`;
    if (session.role) hasuraHeaders["x-hasura-role"] = session.role;

    let tempClient = new ApolloClient({
      uri: process.env.NEXT_PUBLIC_HASURA_URL,
      cache: new InMemoryCache(),
      headers: hasuraHeaders,
    });
    async function buildDataProvider() {
      const hasuraProvider = await buildHasuraProvider(
        { client: tempClient },
        {
          buildFields: customFields,
        },
        customVariables
      );
      setDataProvider(() => hasuraProvider);
      setApolloClient(tempClient);
    }
    buildDataProvider();
  }, [session]);

  if (!dataProvider || !apolloClient) return null;
  return (
    <AdminContext dataProvider={dataProvider}>
      <AsyncResources client={apolloClient} />
    </AdminContext>
  );
}
Example #5
Source File: App.js    From react-sample-projects with MIT License 6 votes vote down vote up
function App() {
  const client = new ApolloClient({
    uri: 'https://graphql-pokemon2.vercel.app/',
    cache: new InMemoryCache(),
  });

  return (
    <ApolloProvider client={client}>
      <Provider store={store}>
        <Router hashType="slash">
          <Routes>
            <Route exact path="/" element={<Home />}></Route>
            <Route
              exact
              path="/pokemon/:id"
              element={<PokemonDetail />}
            ></Route>
          </Routes>
        </Router>
      </Provider>
    </ApolloProvider>
  );
}
Example #6
Source File: apollo-client.js    From graphql-sample-apps with Apache License 2.0 6 votes vote down vote up
createApolloClient = (token) => {
    const httpLink = createHttpLink({
      uri: process.env.REACT_APP_GRAPHQL_ENDPOINT || config["REACT_APP_GRAPHQL_ENDPOINT"],
      options: {
        reconnect: true,
      },
    });

    const authLink = setContext((_, { headers }) => {
      // return the headers to the context so httpLink can read them
      return {
        headers: {
          ...headers,
          "X-Auth-Token": token,
        },
      };
    });

    return new ApolloClient({
      link: authLink.concat(httpLink),
      cache: new InMemoryCache()
    });
  }
Example #7
Source File: API.js    From Dashboard with MIT License 6 votes vote down vote up
client = new ApolloClient({
  uri: 'http://localhost:3100/graphql',
  cache: new InMemoryCache(),
  defaultOptions: {
    query: {
      fetchPolicy: 'no-cache',
      errorPolicy: 'all',
    }
  }
})
Example #8
Source File: client.js    From jamstack-ecommerce with MIT License 6 votes vote down vote up
client = new ApolloClient({
    link: new HttpLink({
        uri: "https://shanstore2.myshopify.com/api/graphql",
        fetch,
        headers: {
            "X-Shopify-Storefront-Access-Token": "a9da41bccc9eb31891047c268e893226"
        }
    }),
    cache: new InMemoryCache()
})
Example #9
Source File: client.js    From bedav with GNU General Public License v3.0 6 votes vote down vote up
export default async function getClient() {
  const cache = new InMemoryCache();

  await persistCache({
    cache,
    storage: new LocalForageWrapper(localForage),
  });

  const client = new ApolloClient({
    cache,
    uri: "/graphql",
  });

  return client;
}
Example #10
Source File: ssrApollo.js    From stacker.news with MIT License 6 votes vote down vote up
export default async function getSSRApolloClient (req, me = null) {
  const session = req && await getSession({ req })
  return new ApolloClient({
    ssrMode: true,
    link: new SchemaLink({
      schema: mergeSchemas({
        schemas: typeDefs,
        resolvers: resolvers
      }),
      context: {
        models,
        me: session
          ? session.user
          : me,
        lnd,
        search
      }
    }),
    cache: new InMemoryCache()
  })
}
Example #11
Source File: ApolloClient.js    From nextjs-woocommerce with GNU General Public License v3.0 6 votes vote down vote up
client = new ApolloClient({
  ssrMode: clientSide,
  link: middleware.concat(
    afterware.concat(
      createHttpLink({
        uri: process.env.NEXT_PUBLIC_GRAPHQL_URL,
        fetch,
      })
    )
  ),
  cache: new InMemoryCache(),
})
Example #12
Source File: common.js    From acy-dex-interface with MIT License 5 votes vote down vote up
chainlinkClient = new ApolloClient({
  uri: CHAINLINK_GRAPH_API_URL,
  cache: new InMemoryCache()
})
Example #13
Source File: apollo.js    From internship-job-portal with MIT License 5 votes vote down vote up
apolloClient = new ApolloClient({
  uri: 'https://48p1r2roz4.sse.codesandbox.io', // TODO change here
  cache: new InMemoryCache(),
})
Example #14
Source File: App.js    From web-frontend with MIT License 5 votes vote down vote up
client = new ApolloClient({
  cache: new InMemoryCache(),
  link: httpLink,
})
Example #15
Source File: App.js    From Simplify-Testing-with-React-Testing-Library with MIT License 5 votes vote down vote up
client = new ApolloClient({
  // uri: 'production url',
  uri: 'http://localhost:4000',
  cache: new InMemoryCache()
})
Example #16
Source File: index.js    From next-ecommerce with MIT License 5 votes vote down vote up
function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === 'undefined',
    link: createIsomorphLink(),
    cache: cache,
  });
}
Example #17
Source File: AppEntry.js    From malware-detection-frontend with Apache License 2.0 5 votes vote down vote up
AppEntry = ({ useLogger, connectToDevTools }) => {
    const tags = useRef();
    const registry = useLogger ? init(logger) : init();
    const selectedWorkloads = useRef();
    const selectedSID = useRef();

    const globalFilterLink = setContext((_, { headers }) => ({
        headers: {
            ...headers,
            ...(tags.current?.length && { 'insights-tags': `${tags.current}` }),
            ...(selectedWorkloads.current?.SAP?.isSelected && { 'insights-sap-system': true }),
            ...(selectedWorkloads.current['Ansible Automation Platform']?.isSelected && { 'insights-ansible-system': true }),
            ...(selectedWorkloads.current['Microsoft SQL']?.isSelected && { 'insights-mssql-system': true }),
            ...(selectedSID.current?.length && { 'insights-sap-sids': `${selectedSID.current}` })
        }
    }));
    const client = useMemo(() =>  new ApolloClient({
        link: globalFilterLink.concat(createHttpLink({
            uri: '/api/malware-detection/v1/graphql'
        })),
        cache,
        connectToDevTools
    }, `${tags.current}`), [connectToDevTools, globalFilterLink]);
    registry.register({ notifications });

    useEffect(() => {
        insights.chrome.init();
        insights.chrome.identifyApp('malware');
        if (insights.chrome?.globalFilterScope) {
            insights.chrome.on('GLOBAL_FILTER_UPDATE', ({ data }) => {
                const [workloads, SID, selectedTags] =
                insights.chrome?.mapGlobalFilter?.(data, false, true) || [];
                tags.current =  selectedTags?.join(',') || '';

                selectedWorkloads.current = workloads || {};
                selectedSID.current = SID || [];

                globalFilters({ workloads, SID, selectedTags });

                client.resetStore();
            });
        }

    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [client]);

    return <IntlProvider locale={navigator.language.slice(0, 2)} messages={messages} onError={console.log}>
        <ApolloProvider client={client}>
            <RegistryContext.Provider value={{ getRegistry: () => registry }}>
                <Provider store={registry.getStore()}>
                    <Router basename={getBaseName(window.location.pathname)}>
                        <NotificationsPortal />
                        <App />
                    </Router>
                </Provider>
            </RegistryContext.Provider>
        </ApolloProvider>
    </IntlProvider>;
}
Example #18
Source File: apollo-client.js    From RC4Community with Apache License 2.0 5 votes vote down vote up
client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache(),
})
Example #19
Source File: index.js    From resume-github with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
})
Example #20
Source File: ApolloClient.js    From ucurtmetre with GNU General Public License v3.0 5 votes vote down vote up
client = new ApolloClient({
  uri: config.endpoint,
  cache: new InMemoryCache(),
})
Example #21
Source File: index.jsx    From Tai-Shang-NFT-Wallet with MIT License 5 votes vote down vote up
client = new ApolloClient({
  uri: subgraphUri,
  cache: new InMemoryCache(),
})
Example #22
Source File: App.jsx    From Consuming-GraphqL-Apollo with MIT License 5 votes vote down vote up
client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: "http://localhost:4000/graphql" // your graphql server link
  }),
  credentials: "same-origin",
})
Example #23
Source File: apolloClient.js    From stack-underflow with MIT License 5 votes vote down vote up
client = new ApolloClient({
  cache: new InMemoryCache({
    typePolicies: {
      Question: {
        fields: {
          upvotedBy: {
            merge(existing, incoming) {
              return incoming;
            },
          },
          downvotedBy: {
            merge(existing, incoming) {
              return incoming;
            },
          },
          comments: {
            merge(existing, incoming) {
              return incoming;
            },
          },
          answers: {
            merge(existing, incoming) {
              return incoming;
            },
          },
          tags: {
            merge(existing, incoming) {
              return incoming;
            },
          },
        },
      },
      Answer: {
        fields: {
          upvotedBy: {
            merge(existing, incoming) {
              return incoming;
            },
          },
          downvotedBy: {
            merge(existing, incoming) {
              return incoming;
            },
          },
          comments: {
            merge(existing, incoming) {
              return incoming;
            },
          },
        },
      },
    },
  }),
  link: authLink.concat(httpLink),
})
Example #24
Source File: historical_price_card.js    From astroport-lbp-frontend with MIT License 5 votes vote down vote up
apolloClient = new ApolloClient({
  uri: 'https://graph.mirror.finance/graphql',
  cache: new InMemoryCache()
})
Example #25
Source File: index.jsx    From moonshot with MIT License 5 votes vote down vote up
client = new ApolloClient({
  uri: subgraphUri,
  cache: new InMemoryCache(),
})
Example #26
Source File: App.js    From ReactNativeApolloOnlineStore with MIT License 5 votes vote down vote up
export default function() {
  const [client, setClient] = React.useState(null);

  React.useEffect(() => {
    persistCache({
      cache,
      storage: AsyncStorage,
      trigger: 'background',
    }).then(() => {
      setClient(
        new ApolloClient({
          uri: GRAPHQL_URL,
          cache: cache,
          resolvers: resolvers,
        }),
      );
    });
  }, []);

  if (!client) {
    return <Loading />;
  }

  return (
    <ApolloProvider client={client}>
      <NavigationContainer>
        <Stack.Navigator
          screenOptions={{
            headerBackTitleVisible: false,
            headerTintColor: 'black',
          }}>
          <Stack.Screen
            name={'ProductsList'}
            component={ProductsList}
            options={{
              headerRight: () => <HeaderFavoriteProductsCount />,
            }}
          />
          <Stack.Screen
            name={'ProductDetails'}
            component={ProductDetails}
            options={{
              headerRight: () => <HeaderFavoriteProductsCount />,
            }}
          />
        </Stack.Navigator>
      </NavigationContainer>
    </ApolloProvider>
  );
}
Example #27
Source File: index.jsx    From quadratic-diplomacy with MIT License 5 votes vote down vote up
client = new ApolloClient({
  uri: subgraphUri,
  cache: new InMemoryCache(),
})
Example #28
Source File: ApolloProvider.js    From climatescape.org with MIT License 5 votes vote down vote up
ApolloProvider = ({ children }) => {
  const { getTokenSilently, isAuthenticated } = useAuth0()
  const {
    site: { siteMetadata },
  } = useStaticQuery(graphql`
    query ApolloProviderQuery {
      site {
        siteMetadata {
          graphqlUri
        }
      }
    }
  `)

  const tokenLink = setContext(async () => {
    if (!isAuthenticated) return {}

    const token = await getTokenSilently()

    if (!token) return {}

    return {
      headers: { Authorization: `Bearer ${token}` },
    }
  })

  const errorLink = onError(error => {
    console.error("Apollo error", error) // eslint-disable-line no-console
  })

  // TODO: This total hack can be removed once we fix site builds with https
  // for now, the ENV var is insecure by default but we need to secure it
  // for the client in order to prevent "mixed content" errors
  const uri = siteMetadata.graphqlUri.replace("http://", "https://")
  const httpLink = new HttpLink({
    uri,
    fetch,
  })

  const apolloClient = new ApolloClient({
    link: ApolloLink.from([tokenLink, errorLink, httpLink]),
    cache: new InMemoryCache(),
  })

  return (
    <VanillaApolloProvider client={apolloClient}>
      {children}
    </VanillaApolloProvider>
  )
}
Example #29
Source File: apollo-client.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
client = new ApolloClient({
    uri: process.env.REACT_APP_GRAPHQL_ENDPOINT || "https://beneficial-baseball-9463.us-west-2.aws.cloud.dgraph.io/graphql",
    cache: new InMemoryCache(),
})