4
votes

React Apollo 2.1 introduce <Query/> component to hook graphql query with component.

<Query query={GET_DOGS}>
{({ loading, error, data }) => {
  if (loading) return "Loading...";
  if (error) return `Error! ${error.message}`;

  return (
    <select name="dog" onChange={onDogSelected}>
      {data.dogs.map(dog => (
        <option key={dog.id} value={dog.breed}>
          {dog.breed}
        </option>
      ))}
    </select>
  );
}}

In older version we use graphql Hoc to hook query.

export default compose(
  graphql(GET_DOGS)(MyComponent),
  withLoader
)(Component)

Here withLoader HOC handles loading, error and data state.

function withLoader(WrappedComponent) {
    class comp extends React.PureComponent {
       render(){
          return this.props.isData?<WrappedComponent {...this.props}/>:<Loading/>
       }
    }
}

So which is best way to hook query and why? Is it wise decision to shift all queries which was written using graphql HOC into latest <Query/> component.

I'm not getting any pros writing a query according Apollo 2.1 . Personally writing a query using hoc looks clean and decoupled. But some people doesn't recommended use hoc.

1
I did not find anything telling that apollo has deprecated the hoc's version, but all apollo's documentation use the Query component, so I think that this is the suggested way.jonathanrz
Are they doing any kind of optimisation to implement Query Component? Because using graphql HOC, components looks clean and decouple from query logic.shah chaitanya

1 Answers

3
votes

IMHO <Query/> components were introduced only to simplify the initial barrier for newcomers. They look like other components and are easy to read.

Their use is limited to simple use cases - using them quickly becomes complicated in more complex scenarios.

Try to use data from <Query/> in other life cycle or try to use a few of them (<Mutation/>) in one render.

You'll quickly be back in composing HOCs ;)