Skip to content

Instantly share code, notes, and snippets.

@adrian-afergon
Created September 15, 2020 09:37
Show Gist options
  • Save adrian-afergon/4cd57b40d510048366032442fda1ffd8 to your computer and use it in GitHub Desktop.
Save adrian-afergon/4cd57b40d510048366032442fda1ffd8 to your computer and use it in GitHub Desktop.
This gist represent how to consume a GraphQL service using the porposal of React Layers
export const ProductContext = React.createContext({
product: {}
})
const ProductAdapter = ({ handle, children }) => {
const { productRepository } = React.useContext(DependenciesContext)
const [product, setProduct] = React.useState()
React.useEffect(() => {
productRepository.getProductByHandle(handle).then(setProduct)
},[handle])
return (
<>{children}</>
)
}
export const ProductProvider = ({
children, handle
}) => {
const { productRepository } = React.useContext(DependenciesContext)
return (
<ApolloProvider client={productRepository.client}>
<ProductAdapter handle={handle}>
{children}
</ProductAdapter>
</ApolloProvider>
)
}
export const useProduct = () => React.useContext(ProductsContext)
export const productRepository = () => {
const client = new ApolloClient({
uri: `${config.PRODUCTS_SERVICE}/graphql`,
cache: new InMemoryCache()
})
const getProductByHandle = async (handle) => client.query({
query: gql`
query($handle: ID!){
GetProduct(handle: $handle) {
id
handle
title
price
}
}`,
variables: { handle }
})
const getProductById = id => client.query({
query: gql`
query($id: ID){
GetProduct(id: $id) {
id
handle
title
price
}
}`,
variables: { id }
})
return {
client,
getProductByHandle,
getProductById
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment