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

react-apollo-hooks-temporary

v0.0.3

Published

React Apollo Hooks.

Downloads

2

Readme

React Apollo - Hooks

npm version Build Status Join the community on Spectrum

React Apollo Hooks.

NOTE: Full React Apollo Hooks usage documentation is coming soon, and when ready will be made available in the main React Apollo documentation. The contents of this README are intended to help beta testers, and will change.

Contents

  1. Installation
  2. Hooks Overview
  1. Reference

Installation

npm install @apollo/react-hooks

Hooks Overview

a) useQuery

Function:

export function useQuery<TData = any, TVariables = OperationVariables>(
  query: DocumentNode,
  options?: QueryHookOptions<TData, TVariables>
): QueryResult<TData, TVariables>;

Options:

query?: DocumentNode;
displayName?: string;
skip?: boolean;
onCompleted?: (data: TData) => void;
onError?: (error: ApolloError) => void;
ssr?: boolean;
variables?: TVariables;
fetchPolicy?: WatchQueryFetchPolicy;
errorPolicy?: ErrorPolicy;
pollInterval?: number;
client?: ApolloClient<any>;
notifyOnNetworkStatusChange?: boolean;
context?: Context;
partialRefetch?: boolean;
returnPartialData?: boolean

Result:

  • client: ApolloClient;
  • data: TData | undefined;
  • error?: ApolloError;
  • loading: boolean;
  • networkStatus: NetworkStatus;
  • fetchMore: any;

Example (from the Hooks demo app):

const GET_ROCKET_INVENTORY = gql`
  query getRocketInventory {
    rocketInventory {
      id
      model
      year
      stock
    }
  }
`;

export function RocketInventoryList() {
  const { loading, data } = useQuery(GET_ROCKET_INVENTORY);
  return (
    <Row className="rocket-inventory-list mt-4">
      <Col sm="12">
        <h3>Available Inventory</h3>
        {loading ? (
          <p>Loading ...</p>
        ) : (
          <table className="table table-striped table-bordered">
            <thead>
              <tr>
                <th>Model</th>
                <th>Year</th>
                <th>Stock</th>
              </tr>
            </thead>
            <tbody>
              {data.rocketInventory.map((inventory: RocketInventory) => (
                <tr
                  key={`${inventory.model}-${inventory.year}-${
                    inventory.stock
                  }`}
                >
                  <td>{inventory.model}</td>
                  <td>{inventory.year}</td>
                  <td>{inventory.stock}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </Col>
    </Row>
  );
}

b) useMutation

Function:

export function useMutation<TData = any, TVariables = OperationVariables>(
  mutation: DocumentNode,
  options?: MutationHookOptions<TData, TVariables>
): MutationTuple<TData, TVariables>;

Options:

mutation?: DocumentNode;
variables?: TVariables;
optimisticResponse?: TData | ((vars: TVariables) => TData);
refetchQueries?: Array<string | PureQueryOptions> | RefetchQueriesFunction;
awaitRefetchQueries?: boolean;
errorPolicy?: ErrorPolicy;
update?: MutationUpdaterFn<TData>;
client?: ApolloClient<object>;
notifyOnNetworkStatusChange?: boolean;
context?: Context;
onCompleted?: (data: TData) => void;
onError?: (error: ApolloError) => void;
fetchPolicy?: WatchQueryFetchPolicy;
ignoreResults?: boolean;

Result:

[
  (
    options?: MutationFunctionOptions<TData, TVariables>
  ) => Promise<void | ExecutionResult<TData>>,
  {
    data?: TData;
    error?: ApolloError;
    loading: boolean;
    called: boolean;
    client?: ApolloClient<object>
  }
];

Example (from the Hooks demo app):

const SAVE_ROCKET = gql`
  mutation saveRocket($rocket: RocketInput!) {
    saveRocket(rocket: $rocket) {
      model
    }
  }
`;

export function NewRocketForm() {
  const [model, setModel] = useState('');
  const [year, setYear] = useState(0);
  const [stock, setStock] = useState(0);

  const [saveRocket, { error, data }] = useMutation<
    {
      saveRocket: RocketInventory;
    },
    { rocket: NewRocketDetails }
  >(SAVE_ROCKET, {
    variables: { rocket: { model: model, year: +year, stock: +stock } },
    refetchQueries: ['getRocketInventory']
  });

  return (
    <div className="new-rocket-form mt-3">
      <h3>Add a Rocket</h3>
      {error ? <Alert color="danger">Oh no! {error.message}</Alert> : null}
      {data && data.saveRocket ? (
        <Alert color="success">
          Model <strong>{data.saveRocket.model}</strong> added!
        </Alert>
      ) : null}
      <Form style={{ border: '1px solid #ddd', padding: '15px' }}>
        <Row>
          <Col sm="6">
            <FormGroup>
              <Label for="model">Model</Label>
              <Input
                type="text"
                name="model"
                id="model"
                onChange={e => setModel(e.target.value)}
              />
            </FormGroup>
          </Col>
          <Col sm="3">
            <FormGroup>
              <Label for="year">Year</Label>
              <Input
                type="number"
                name="year"
                id="year"
                onChange={e => setYear(+e.target.value)}
              />
            </FormGroup>
          </Col>
          <Col sm="3">
            <FormGroup>
              <Label for="stock">Stock</Label>
              <Input
                type="number"
                name="stock"
                id="stock"
                onChange={e => setStock(+e.target.value)}
              />
            </FormGroup>
          </Col>
        </Row>
        <Row>
          <Col
            sm="12"
            className="text-right"
            onClick={e => {
              e.preventDefault();
              if (model && year && stock) {
                saveRocket();
              }
            }}
          >
            <Button>Add</Button>
          </Col>
        </Row>
      </Form>
    </div>
  );
}

c) useSubscription

Function:

export function useSubscription<TData = any, TVariables = OperationVariables>(
  subscription: DocumentNode,
  options?: SubscriptionHookOptions<TData, TVariables>
);

Options:

subscription?: DocumentNode;
variables?: TVariables;
fetchPolicy?: FetchPolicy;
shouldResubscribe?: boolean | ((options: BaseSubscriptionOptions<TData, TVariables>) => boolean);
client?: ApolloClient<object>;
onSubscriptionData?: (options: OnSubscriptionDataOptions<TData>) => any;
onSubscriptionComplete?: () => void;

Example (from the Hooks demo app):

const LATEST_NEWS = gql`
  subscription getLatestNews {
    latestNews {
      content
    }
  }
`;

export function LatestNews() {
  const { loading, data } = useSubscription<News>(LATEST_NEWS);
  return (
    <Card className="bg-light">
      <CardBody>
        <CardTitle>
          <h5>Latest News</h5>
        </CardTitle>
        <CardText>{loading ? 'Loading...' : data!.latestNews.content}</CardText>
      </CardBody>
    </Card>
  );
}

d) useApolloClient

Function:

export function useApolloClient(): ApolloClient<object>;

Result:

ApolloClient instance stored in the current Context.

Example:

const client = useApolloClient();
consol.log('AC instance stored in the Context', client);

Reference