Created
September 15, 2020 09:37
-
-
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
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
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) |
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
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