Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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