Skip to content

Instantly share code, notes, and snippets.

@jaydenseric
Created July 2, 2019 03:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaydenseric/5ff7ebeafca16da32a9fdb9055e99e1e to your computer and use it in GitHub Desktop.
Save jaydenseric/5ff7ebeafca16da32a9fdb9055e99e1e to your computer and use it in GitHub Desktop.
A <DeferredQuery> react component that loads a react-apollo <Query> on demand.
import React from 'react'
import { Query } from 'react-apollo'
export const DeferredQuery = ({ children, ...props }) => {
const [skip, setSkip] = React.useState(true)
const load = () => setSkip(false)
return (
<Query skip={skip} {...props}>
{args => children({ ...args, load })}
</Query>
)
}
DeferredQuery.propTypes = Query.propTypes
import React from 'react'
import gql from 'graphql-tag'
import { DeferredQuery } from './DeferredQuery.jsx'
const EXAMPLE_QUERY = gql`
{
user {
name
}
}
`
export const Example = () => (
<DeferredQuery query={EXAMPLE_QUERY}>
{({ load, loading, error, data }) =>
data ? (
<p>{data.user.name}</p>
) : error ? (
<p>Loading failed!</p>
) : (
<button onClick={load} disabled={loading}>Load</button>
)
}
</DeferredQuery>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment