Skip to content

Instantly share code, notes, and snippets.

@jamesreggio
Created June 5, 2018 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesreggio/6dd299b608f38d531a6822d0b2478cd9 to your computer and use it in GitHub Desktop.
Save jamesreggio/6dd299b608f38d531a6822d0b2478cd9 to your computer and use it in GitHub Desktop.
MetaQuery example in reply to @gunar
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