diff --git a/examples/next/pages/search.js b/examples/next/pages/search.js index 78c643b..63511cc 100644 --- a/examples/next/pages/search.js +++ b/examples/next/pages/search.js @@ -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 }); @@ -28,7 +28,7 @@ const SearchResult = ({ q }) => ( !q || q.length < 2} > {({ data: { allPosts }, loading, skipped }) => skipped || !allPosts ? ( @@ -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 diff --git a/src/Query.js b/src/Query.js index bd215a1..f7ce041 100644 --- a/src/Query.js +++ b/src/Query.js @@ -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 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); } } @@ -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; } } @@ -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 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