Created
June 5, 2018 18:24
-
-
Save jamesreggio/6dd299b608f38d531a6822d0b2478cd9 to your computer and use it in GitHub Desktop.
MetaQuery example in reply to @gunar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ProductsQueryWithConfigurableFragment = ` | |
query { | |
products { | |
...ProductFragment | |
} | |
} | |
`; | |
const SlimProductFragment = ` | |
fragment ProductFragment on Product { | |
id | |
name | |
price | |
} | |
` | |
const FullProductFragment = ` | |
fragment ProductFragment on Product { | |
id | |
name | |
price | |
reviews { | |
...you get the idea | |
} | |
} | |
`; | |
const QueryCache = new WeakMap(); | |
const MetaQuery = ({query, fragment, ...props}) => { | |
if (!QueryCache.has(query)) { | |
QueryCache.set(query, new WeakMap()); | |
} | |
if (!QueryCache.get(query).has(fragment)) { | |
const composedQuery = gql` | |
${query} | |
${fragment} | |
`; | |
QueryCache.get(query).set(fragment, composedQuery); | |
} | |
const composedQuery = QueryCache.get(query).get(fragment); | |
return <Query query={composedQuery} {...props} />; | |
} | |
const App = () => ( | |
<Fragment> | |
<MetaQuery query={ProductsQueryWithConfigurableFragment} fragment={SlimProductFragment}> | |
{({data}) => <SlimProducts data={data} />} | |
</MetaQuery> | |
<MetaQuery query={ProductsQueryWithConfigurableFragment} fragment={FullProductFragment}> | |
{({data}) => <FullProducts data={data} />} | |
</MetaQuery> | |
</Fragment> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment