npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

qwik-graphql-client

v0.2.3

Published

Introducing the Qwik GraphQL Client - the coolest cat on the block when it comes to consuming GraphQL APIs! This package is the ultimate wingman for your Qwik projects, giving you all the tools you need to easily retrieve data from GraphQL servers

Downloads

83

Readme

qwik-graphql-request

Simple GraphQL client and hook for Qwik applications build upon Apollo Client.

npm version

Highlights

  • Simple GraphQL client for Qwik applications.
  • Built on top of the Apollo Client core.
  • Fully typesafe with GraphQL Typed Document Nodes.
  • Creates one reusable GraphQL client per application.
  • Built in useQuery hook to simplify GraphQL requests in Qwik.
  • Works seamlessly with Qwik's <Resource> component.
  • Reactive to variables passed into the query.

Installation

npm add qwik-graphql-client
pnpm add qwik-graphql-client
yarn add qwik-graphql-client

Qwik Start

Provide a GraphQL client context to child components. The context will be used by hooks to make GraphQL requests. To reuse your client throughout your entire application you can provide it in the root component as shown here.

import {
  GraphQLClientProvider,
  ApolloClient,
  InMemoryCache,
} from "qwik-graphql-client";

export default component$(() => {
  return (
    <GraphQLClientProvider
      clientGenerator$={$(
        () =>
          new ApolloClient({
            cache: new InMemoryCache(),
            uri: "http://localhost:2003/graphql",
          })
      )}
    >
      <Slot />
    </GraphQLClientProvider>
  );
});

Then in child components you can use the useQuery hook to make GraphQL requests and consume them using Qwik's <Resource> component.

import { useQuery, gql } from "qwik-graphql-client";

export default component$(() => {
  const variables = useStore({
    artistID: "1",
  });

  const artist = useQuery(
    gql`
      query GetArtist($artistID: ID!) {
        artist(artistID: $artistID) {
          stageName
          name
        }
      }
    `,
    variables
  );

  return (
    <Resource
      value={artist}
      onResolved={(value) => <pre>{artist.stageName}</pre>}
      onPending={...}
      onRejected={...}
    />
  )
});

Examples

Provide Context To Entire Application

To reuse your client throughout your entire application you can provide it in the root component.

import {
  GraphQLClientProvider,
  ApolloClient,
  InMemoryCache,
} from "qwik-graphql-client";

export default component$(() => {
  return (
    <QwikCityProvider>
      <head>...</head>
      <body>
        <GraphQLClientProvider
          clientGenerator$={$(
            () =>
              new ApolloClient({
                cache: new InMemoryCache(),
                uri: "http://localhost:2003/graphql",
              })
          )}
        >
          <RouterOutlet />
        </GraphQLClientProvider>
        <ServiceWorkerRegistry />
      </body>
    </QwikCityProvider>
  );
});

Using a Client Without the Context Provider

You can use a GraphQL a separate client independently of the context provider by passing a clientGenerator$ function into hooks. Note: This only works with useLazyQuery and useMutation hooks.

import {
  QwikGraphQLClient,
  ApolloClient,
  InMemoryCache,
} from "qwik-graphql-client";

export const useHero = (artistID: string) => {
  return useLazyQuery(
    gql`
      query GetArtist($artistID: ID!) {
        artist(artistID: $artistID) {
          stageName
          name
        }
      }
    `,
    { artistID },
    {
      clientGenerator$: $(
        () =>
          new ApolloClient({
            cache: new InMemoryCache(),
            uri: "http://localhost:2003/graphql",
          })
      ),
    }
  );
};

Using useLazyQuery

The useLazyQuery hook is also available to use. It works the same as the useQuery hook except it does not automatically execute the query. Instead it returns a function that can be called to execute the query.

import { useLazyQuery, gql } from "qwik-graphql-client";

export default component$(() => {
  const {executeQuery$, data} = useLazyQuery(
    gql`
      query GetArtist($artistID: ID!) {
        artist(artistID: $artistID) {
          stageName
          name
        }
      }
    `,
    { artistID: "1" }
  );

  return (
    <div>
      <button onClick={() => executeQuery()}>Get Hero</button>
      <Resource
        value={data}
        onResolved={(value) => <div>{value.stageName}</div>}
        onPending={...}
        onRejected={...}
      />
    </div>
})

Using useMutation

The useMutation hook allows creating mutations to graphql servers. It works the similar to the useLazyQuery hook in that it returns a function that can be called to execute the mutation.

import { useLazyQuery, gql } from "qwik-graphql-client";

export default component$(() => {
  const variables = useStore({
    name: "Stefani Joanne Angelina Germanotta",
    stageName: "Lady Gaga"
  })

  const {executeQuery$, data} = useLazyQuery(
    gql`
      mutation AddArtist($name: String!, $stageName: String!) {
        hero(name: $name, stageName: $stageName) {
          id
        }
      },
      variables
    `,
  );

  return (
    <div>
      <button onClick={() => getHero()}>Get Hero</button>
      <Resource
        value={data}
        onResolved={(value) => <div>{value.name}</div>}
        onPending={...}
        onRejected={...}
      />
    </div>
})

Passing in default headers and middleware to the client

You can pass in default headers and middleware that will be sent with every request in the useQuery hook.

import {
  GraphQLClientProvider,
  ApolloClient,
  InMemoryCache,
  HttpLink,
  ApolloLink,
  concat,
} from "qwik-graphql-client";

export default component$(() => {
  const clientGenerator$ = $(() => {
    const httpLink = new HttpLink({
      uri: "http://localhost:2003/graphql",
    });

    const requestMiddleware = new ApolloLink((operation, forward) => {
      console.log("request", operation);
      return forward(operation);
    });

    const responseMiddleware = new ApolloLink((operation, forward) => {
      console.log("response", operation);
      return forward(operation);
    });

    return new ApolloClient({
      cache: new InMemoryCache(),
      link: requestMiddleware.concat(concat(middleware, httpLink)),
      headers: {
        Authorization: "Bearer 123",
      },
    });
  });

  return (
    <GraphQLClientProvider clientGenerator$={clientGenerator$}>
      <Slot />
    </GraphQLClientProvider>
  );
});

Enabling Apollo Client Devtools

To enable linking to the Apollo Client Devtools browser extension (Chrome, Firefox), add the following line to the Apollo Client returned from the clientGenerator$.

new ApolloClient({
  // Enable in development only.
  connectToDevTools: import.meta.env.DEV,
  // Enable always.
  connectToDevTools: true,
  ...
});

Limitations

While this library is built on top of Apollo Client Core and the Apollo Client docs can be used for further documentation, this package does not support all of the features and some features are likely not to work as expected. This is very much a work in progress. If you find a bug or would like to see a feature added please open an issue or create a pull request.

Contributing

Contributions are welcome and appreciated, please open an issue and/or create a pull request.

Contributors