Skip to content
This repository has been archived by the owner on Apr 19, 2023. It is now read-only.

Commit

Permalink
Avoid a request completely when skipped
Browse files Browse the repository at this point in the history
  • Loading branch information
slaskis committed Jan 18, 2018
1 parent 8c49e5b commit 470b7b7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 14 deletions.
6 changes: 3 additions & 3 deletions examples/next/pages/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Query } from "@department/apollo-component";
import withApollo from "../components/withApollo";

class Search extends React.Component {
state = { q: "" };
state = {};

query = e => {
this.setState({ q: e.target.value });
Expand All @@ -28,7 +28,7 @@ const SearchResult = ({ q }) => (
<Query
gql={SearchQuery}
variables={{ q }}
skip={q.length < 2} // try with just a bool
skip={({ q }) => !q || q.length < 2}
>
{({ data: { allPosts }, loading, skipped }) =>
skipped || !allPosts ? (
Expand All @@ -52,7 +52,7 @@ const SearchResult = ({ q }) => (
);

const SearchQuery = gql`
query Search($q: String) {
query Search($q: String!) {
allPosts(filter: { description_contains: $q }) {
id
description
Expand Down
29 changes: 18 additions & 11 deletions src/Query.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,10 @@ export class Query extends React.Component {
}

componentWillMount() {
const { client, queued } = this.context.apollo || {};
if (!client) {
throw new Error(
"missing apollo client in context. is there a <Provider /> ancestor component?"
);
}

this.observable = client.watchQuery(propsToOptions(this.props));
const { queued } = this.context.apollo || {};

if (!this.props.lazy && queued) {
// skip rendering if no
if (!this.props.lazy && !this.state.skipped && queued) {
queued.push(this.observable);
}
}
Expand All @@ -52,8 +46,8 @@ export class Query extends React.Component {
delete this.subscription;
}

if (this.observable) {
delete this.observable;
if (this._o) {
delete this._o;
}
}

Expand All @@ -72,6 +66,19 @@ export class Query extends React.Component {
}
}

get observable() {
if (this._o) {
return this._o;
}
const { client } = this.context.apollo || {};
if (!client) {
throw new Error(
"missing apollo client in context. is there a <Provider /> ancestor component?"
);
}
return (this._o = client.watchQuery(propsToOptions(this.props)));
}

request(props) {
const skipped = this.shouldSkip(props);
// set state to make sure we render even
Expand Down

0 comments on commit 470b7b7

Please sign in to comment.