Apollo Component
A render component for easy querying and mutating of your GraphQL API.
Install
npm install @department/apollo-component
Examples
Here is an example of fetching and rendering the data of an imaginary Order
.
import { gql } from "graphql-tag"
import { Query } from "@department/apollo-component"
import SingleOrder, { LoadingOrder } from "components/SingleOrder"
import { GenericError, NotFound } from "components/Errors"
const ShowOrderQuery = gql`
query ShowOrder($id: ID!) {
Order(id: $id) {
...SingleOrder
}
}
${SingleOrder.fragments.SingleOrder}
`;
const Show = ({ id }) => (
<Query gql={ShowOrderQuery} variables={{id}}>
{({ data: { Order }, loading, error, refetch }) =>
loading ? (
<LoadingOrder />
) : error ? (
<GenericError error={error} />
) : (
<SingleOrder {...Order} update={refetch} />
)}
</Query>
));
And another example using <Mutate/>
and fail
-props to raise any errors to
the nearest
React 16+ Error Boundary:
import { gql } from "graphql-tag";
import { Mutate, Query } from "@department/apollo-component";
import { Exception } from "components/Exception";
const IncrementMutation = gql`
mutation IncrementMutation($num: Int!) {
incr(num: $num)
}
`;
const ShowCountQuery = gql`
query ShowCount {
count
}
`;
const IncrementView = ({ id }) => (
<Exception>
<Query gql={ShowCount} wait fail>
{({ data: { count } }) => <div>Current count: {count}</div>}
</Query>
<Mutate gql={IncrementMutation} refetchQueries={["ShowCount"]} fail>
{incr => (
<form onSubmit={e => incr({ num: e.currentTarget.num.valueAsNumber })}>
<input type="number" name="num" value={1} step={1} />
<button>+</button>
</form>
)}
</Mutate>
</Exception>
);
API
<Query />
Available Props:
Arguments in render callback
- QueryResults
data
the loaded data or an empty objectloading
true while loading (unless the wait
-prop was set)error
Error object if there was any error (unless the fail
-props was
set)refetch(variables)
call this function rerun query with, optionally, new
variablesfetchMore(opts)
call this function to fetch more (read about the
opts)
Example:
({ data: { stuff }, loading }) => <div>{loading ? "loading..." : stuff}</div>;
<Mutate />
Available Props:
gql
refetchQueries
optimisticResponse
update
Arguments in render callback
Mutate(variables)
call this function to trigger the mutation- QueryResults (same as for Query)
data
loading
error
refetch
fetchMore
Example:
(mutate, { data: { stuff }, loading }) => (
<button onClick={() => mutate()} disabled={loading}>
{loading ? "loading..." : stuff}
</button>
);