Skip to content

Instantly share code, notes, and snippets.

@edorivai
Created March 18, 2020 09:56
Show Gist options
  • Save edorivai/48e8fbc965c5a20bddc455349ac4006c to your computer and use it in GitHub Desktop.
Save edorivai/48e8fbc965c5a20bddc455349ac4006c to your computer and use it in GitHub Desktop.
Example of vendure react integration with graphql-codegen hooks
import React from "react";
import { notify } from '@vendure/ui-devkit';
import { gql } from 'graphql-tools';
import { useGetProductsLazyQuery, useToggleEnabledMutation } from './generated-by-codegen';
// These queries get detected and processed by graphql-codegen
const GET_PRODUCTS = gql`
query GetProducts($skip: Int, $take: Int) {
products(options: { skip: $skip, take: $take }) {
items { id, name, enabled },
totalItems
}
}
`;
const TOGGLE_ENABLED = gql`
mutation ToggleEnabled($id: ID!, $enabled: Boolean!) {
updateProduct(input: { id: $id, enabled: $enabled }) {
id
enabled
}
}
`;
export function ProductList() {
const [getProducts, { data }] = useGetProductsLazyQuery({ variables: { skip: 0, take: 10 }});
const [toggleEnabled] = useToggleEnabledMutation();
return <>
<button className="btn btn-primary" onClick={getProducts}>Get products</button>
{
data?.products.length ? <h3>Products</h3> : ''
}
<ol className="product-list">
{data?.products.map(product => <li key={product.id}>
{product.name}
{product.enabled ? <span className="label label-success">Enabled</span> :
<span className="label label-danger">Disabled</span>}
<button
className="btn btn-sm btn-secondary"
onClick={async () => {
await toggleEnabled({
variables: {
id: product.id,
enabled: !product.enabled
}
});
notify({
message: 'Updated Product',
});
}
>
toggle
</button>
</li>)}
</ol>
</>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment