项目作者: department-stockholm

项目描述 :
A render component for easy querying and mutating of your GraphQL API.
高级语言: JavaScript
项目地址: git://github.com/department-stockholm/apollo-component.git
创建时间: 2017-11-24T07:54:11Z
项目社区:https://github.com/department-stockholm/apollo-component

开源协议:ISC License

下载


Apollo Component

npm version

A render component for easy querying and mutating of your GraphQL API.

Install

  1. npm install @department/apollo-component

Examples

Here is an example of fetching and rendering the data of an imaginary Order.

  1. import { gql } from "graphql-tag"
  2. import { Query } from "@department/apollo-component"
  3. import SingleOrder, { LoadingOrder } from "components/SingleOrder"
  4. import { GenericError, NotFound } from "components/Errors"
  5. const ShowOrderQuery = gql`
  6. query ShowOrder($id: ID!) {
  7. Order(id: $id) {
  8. ...SingleOrder
  9. }
  10. }
  11. ${SingleOrder.fragments.SingleOrder}
  12. `;
  13. const Show = ({ id }) => (
  14. <Query gql={ShowOrderQuery} variables={{id}}>
  15. {({ data: { Order }, loading, error, refetch }) =>
  16. loading ? (
  17. <LoadingOrder ></LoadingOrder>
  18. ) : error ? (
  19. <GenericError error={error} ></GenericError>
  20. ) : (
  21. <SingleOrder {...Order} update={refetch} ></SingleOrder>
  22. )}
  23. </Query>
  24. ));

And another example using <Mutate></Mutate> and fail-props to raise any errors to
the nearest
React 16+ Error Boundary:

  1. import { gql } from "graphql-tag";
  2. import { Mutate, Query } from "@department/apollo-component";
  3. import { Exception } from "components/Exception";
  4. const IncrementMutation = gql`
  5. mutation IncrementMutation($num: Int!) {
  6. incr(num: $num)
  7. }
  8. `;
  9. const ShowCountQuery = gql`
  10. query ShowCount {
  11. count
  12. }
  13. `;
  14. const IncrementView = ({ id }) => (
  15. <Exception>
  16. <Query gql={ShowCount} wait fail>
  17. {({ data: { count } }) => <div>Current count: {count}</div>}
  18. </Query>
  19. <Mutate gql={IncrementMutation} refetchQueries={["ShowCount"]} fail>
  20. {incr => (
  21. <form onSubmit={e => incr({ num: e.currentTarget.num.valueAsNumber })}>
  22. <input type="number" name="num" value={1} step={1} />
  23. <button>+</button>
  24. </form>
  25. )}
  26. </Mutate>
  27. </Exception>
  28. );

API

<Query ></Query>

Available Props:

  • gql
  • wait
  • lazy
  • fail
  • skip
  • variables

Arguments in render callback

  • QueryResults
    • data the loaded data or an empty object
    • loading true while loading (unless the wait-prop was set)
    • skipped true if the request was skipped (using the skip-prop)
    • error Error object if there was any error (unless the fail-props was
      set)
    • refetch(variables) call this function rerun query with, optionally, new
      variables
    • fetchMore(opts) call this function to fetch more (read about the
      opts)
Example:
  1. ({ data: { stuff }, loading }) => <div>{loading ? "loading..." : stuff}</div>;

<Mutate ></Mutate>

Available Props:

  • gql
  • refetchQueries
  • optimisticResponse
  • update

Arguments in render callback

  • Mutate(variables) call this function to trigger the mutation
  • QueryResults (like for Query but without skipped)
    • data
    • loading
    • error
    • refetch
    • fetchMore
Example:
  1. (mutate, { data: { stuff }, loading }) => (
  2. <button onClick={() => mutate()} disabled={loading}>
  3. {loading ? "loading..." : stuff}
  4. </button>
  5. );

renderState(client, component, options)

For server side rendering renderState() may be used. It uses a query queue in
the React Context which is populated by <Query></Query> in its componentWillMount()
lifecycle method using a naïve component renderer.

It will by default render the tree repeatedly until all queries, without the
lazy-prop has been completed but the maximum “depth” may be adjusted with the
maxDepth option.

Arguments

  • client an instance of ApolloClient
  • component the root component, will be wrapped by a <Provider ></Provider> with a
    queue
  • RenderStateOptions
    • maxDepth number of attempts to render the tree, defaults to Infinity
      (until no more queries are to be found)

Example

An example which could be used to server side render.

Note how the <Provider></Provider> is not needed in renderState(), it’s because it
wraps the component with a special one.

  1. function renderHTML() {
  2. return renderState(client, <App ></App>, { maxDepth: 1 })
  3. .then(() =>
  4. ReactDOM.renderToString(
  5. <Provider client={client}>
  6. <App ></App>
  7. </Provider>
  8. )
  9. )
  10. .catch(err => {
  11. // you can let the error throw here
  12. // or ignore it and let the client side
  13. // handle it inline
  14. console.error("failed to render state:", err);
  15. return renderErrorPage(err);
  16. });
  17. }