@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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
Source File: index.js    From readr-coverages with MIT License 5 votes vote down vote up
export async function getStaticProps() {
  const client = new ApolloClient({
    uri: process.env.NEXT_PUBLIC_CMS_ENDPOINT,
    cache: new InMemoryCache(),
  });

  const POST_ID = 2641;

  const { contentApiData, ...meta } = (
    await client.query({
      query: gql`
        query posts {
          Post(where: { id: ${POST_ID} }) {
            contentApiData

            title: name
            ogTitle
            ogDescription
            ogImage {
              urlOriginal
            }
            tags {
              name
            }
            publishTime
            updatedAt
          }
        }
      `,
    })
  ).data.Post;

  const story = archieml.load(
    JSON.parse(contentApiData)
      .filter((item) => item.type === 'unstyled' || item.type === 'annotation')
      .map((item) => item.content)
      // .flatMap(function (item) {
      //   if (item.type === 'unstyled') {
      //     return item.content;
      //   }

      //   const text = '{"text":"';
      //   return item.content.map((str) =>
      //     str
      //       .split(/<!--__ANNOTATION__=|-->/gm)
      //       .filter((str) => str && !str.startsWith('<!--'))
      //       .map((str) =>
      //         str.includes(text)
      //           ? str.slice(text.length, str.indexOf('","annotation"'))
      //           : str
      //       )
      //       .join('')
      //   );
      // })
      .join('\n')
  );

  // console.log(
  //   JSON.parse(contentApiData)
  //     .filter((item) => item.type === 'unstyled')
  //     .flatMap((item) => item.content)
  //     .join('\n')
  // );

  return {
    props: {
      meta,
      story,
    },
  };
}
Example #13
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 #14
Source File: _app.js    From redis-examples with MIT License 5 votes vote down vote up
client = new ApolloClient({
  uri: "https://graphql-us-east-1.upstash.io/",
  cache: new InMemoryCache(),
  link,
})
Example #15
Source File: ApolloWrapper.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
ApolloWrapper = () => {
  const { isAuthenticated, getIdTokenClaims } = useAuth0();
  const [xAuthToken, setXAuthToken] = useState("");

  useEffect(() => {
    const getToken = async () => {
      const token = isAuthenticated ? await getIdTokenClaims() : "";
      setXAuthToken(token);
    };
    getToken();
  }, [getIdTokenClaims, isAuthenticated]);

  const httpLink = createHttpLink({
    uri: process.env.REACT_APP_BACKEND_ENDPOINT,
  });

  const authLink = setContext((_, { headers, ...rest }) => {
    if (!xAuthToken) return { headers, ...rest };

    return {
      ...rest,
      headers: {
        ...headers,
        "X-Auth-Token": xAuthToken.__raw,
      },
    };
  });

  const wsLink = new WebSocketLink({
    uri: process.env.REACT_APP_BACKEND_ENDPOINT.replace("https://", "wss://"),
    options: {
      reconnect: true,
      minTimeout: 30000,
      connectionParams: {
        "X-Auth-Token": xAuthToken.__raw,
      },
    },
  });

  const splitLink = split(
    ({ query }) => {
      const definition = getMainDefinition(query);
      return (
        definition.kind === "OperationDefinition" &&
        definition.operation === "subscription"
      );
    },
    wsLink,
    authLink.concat(httpLink)
  );

  const client = new ApolloClient({
    cache: new InMemoryCache(),
    link: splitLink,
  });

  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  );
}
Example #16
Source File: App.js    From ReactCookbook-source with MIT License 5 votes vote down vote up
client = new ApolloClient({
  uri: 'http://localhost:5000',
  cache: new InMemoryCache(),
})
Example #17
Source File: client.js    From horondi_admin with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link: authLink.concat(createUploadLink({ uri: REACT_APP_API_URL })),
  cache: new InMemoryCache({
    addTypename: false,
    fragmentMatcher
  })
})
Example #18
Source File: client.js    From horondi_client_fe with MIT License 5 votes vote down vote up
client = new ApolloClient({
  fetch,
  link: ApolloLink.from([terminatingLink]),
  cache: new InMemoryCache({
    addTypename: false,
    fragmentMatcher
  })
})
Example #19
Source File: client.js    From jamstack-serverless with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link: new HttpLink({
    uri: 'http://localhost:8888/.netlify/functions/graphql_faunadb',
    fetch,
  }),
  cache: new InMemoryCache()
})
Example #20
Source File: seed-db.js    From grandcast.fm with Apache License 2.0 5 votes vote down vote up
client = new ApolloClient({
  link: new HttpLink({ uri, fetch }),
  cache: new InMemoryCache(),
})
Example #21
Source File: apolloClient.js    From realworld with MIT License 5 votes vote down vote up
function createApolloClient(ctx) {
  const ssrMode = typeof window === 'undefined';

  return new ApolloClient({
    assumeImmutableResults: true,
    connectToDevTools: !ssrMode && process.env.NODE_ENV !== 'production',
    ssrMode,
    name: 'Condit',
    version: '1.0.0',
    link: ApolloLink.from([
      setContext(() => {
        const { authorization } = ssrMode
          ? cookie.parse(ctx?.req?.headers?.cookie ?? '')
          : cookie.parse(document.cookie);
        return {
          headers: { authorization },
        };
      }),
      new HttpLink({
        uri: process.env.NEXT_PUBLIC_GRAPHQL_URL, // Server URL (must be absolute)
        credentials: 'omit', // Additional fetch() options like `credentials` or `headers`
      }),
    ]),
    cache: new InMemoryCache({
      resultCaching: true,
      dataIdFromObject(object) {
        switch (object.__typename) {
          case 'Article':
            return `${object.__typename}:${object.slug}`;
          case 'User':
            return `${object.__typename}:${object.username}`;
          default:
            return defaultDataIdFromObject(object);
        }
      },
      typePolicies: {
        Article: {
          keyFields: ['slug'],
        },
        User: {
          keyFields: ['username'],
        },
        Query: {
          fields: {
            articlesConnection: relayStylePagination(),
            articleBySlug(_, { args, toReference }) {
              return toReference({ __typename: 'Article', slug: args.slug });
            },
            comment(_, { args, toReference }) {
              return toReference({ __typename: 'Comment', id: args.id });
            },
            feedConnection: relayStylePagination(),
            userByUsername(_, { args, toReference }) {
              return toReference({
                __typename: 'User',
                username: args.username,
              });
            },
            tag(_, { args, toReference }) {
              return toReference({ __typename: 'Tag', id: args.id });
            },
          },
        },
      },
    }),
  });
}
Example #22
Source File: server.js    From react-workshop with MIT License 5 votes vote down vote up
server
  .disable('x-powered-by')
  .use(express.static(process.env.RAZZLE_PUBLIC_DIR))
  .get('/*', (req, res) => {
    const apolloClient = new ApolloClient({
      ssrMode: true,
      cache: new InMemoryCache(),
      link: createHttpLink({
        uri: 'https://asia-southeast2-minitokopedia.cloudfunctions.net/graphql',
      }),
    });

    const context = {};
    const markup = (
      <ApolloProvider client={apolloClient}>
        <StaticRouter context={context} location={req.url}>
          <App />
        </StaticRouter>
      </ApolloProvider>
    );

    if (context.url) {
      res.redirect(context.url);
    } else {
      getDataFromTree(markup).then((content) => {
        const initialState = apolloClient.extract();

        const html = renderToString(
          <html lang="en">
            <head>
              <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
              <meta charset="utf-8" />
              <title>Welcome to Razzle</title>
              <meta name="viewport" content="width=device-width, initial-scale=1" />
              {cssLinksFromAssets(razzleAssets, 'client')}
            </head>
            <body>
              <div id="root" dangerouslySetInnerHTML={{ __html: content }} />
              <script
                dangerouslySetInnerHTML={{
                  __html: `window.__APOLLO_STATE__=${JSON.stringify(initialState).replace(/</g, '\\u003c')};`,
                }}
              />
              {jsScriptTagsFromAssets(razzleAssets, 'client')}
            </body>
          </html>,
        );

        res.status(200).header('Content-Type', 'text/html').send(`<!doctype html>\n${html}`);
      });
    }
  });
Example #23
Source File: index.js    From openeew-dashboard with Apache License 2.0 5 votes vote down vote up
client = new ApolloClient({
  uri: 'api/graphql',
  cache: new InMemoryCache(),
  credentials: 'include',
})
Example #24
Source File: uniswapClient.js    From SimpleFi with GNU General Public License v3.0 5 votes vote down vote up
uniswapClient = new ApolloClient({
  uri: 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2',
  cache: new InMemoryCache()
})
Example #25
Source File: client.js    From jamstack-serverless with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link: new HttpLink({
    uri: '.netlify/functions/graphql_mongodb',
    fetch,
  }),
  cache: new InMemoryCache()
})
Example #26
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 #27
Source File: common.js    From acy-dex-interface with MIT License 5 votes vote down vote up
arbitrumGraphClient = new ApolloClient({
  uri: ARBITRUM_GRAPH_API_URL,
  cache: new InMemoryCache()
})
Example #28
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 #29
Source File: App.js    From web-frontend with MIT License 5 votes vote down vote up
client = new ApolloClient({
  cache: new InMemoryCache(),
  link: httpLink,
})