ProductList.tsx 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { NotificationService } from '@vendure/admin-ui/core';
  2. import { Link, useInjector, useMutation, useQuery } from '@vendure/admin-ui/react';
  3. import gql from 'graphql-tag';
  4. import React from 'react';
  5. const GET_PRODUCTS = gql`
  6. query GetProducts($skip: Int, $take: Int) {
  7. products(options: { skip: $skip, take: $take }) {
  8. items {
  9. id
  10. name
  11. enabled
  12. }
  13. totalItems
  14. }
  15. }
  16. `;
  17. const TOGGLE_ENABLED = gql`
  18. mutation ToggleEnabled($id: ID!, $enabled: Boolean!) {
  19. updateProduct(input: { id: $id, enabled: $enabled }) {
  20. id
  21. enabled
  22. }
  23. }
  24. `;
  25. export function ProductList() {
  26. const { data, loading, error } = useQuery(GET_PRODUCTS, { skip: 0, take: 10 });
  27. const [toggleEnabled] = useMutation(TOGGLE_ENABLED);
  28. const notificationService = useInjector(NotificationService);
  29. function onToggle(id: string, enabled: boolean) {
  30. toggleEnabled({ id, enabled }).then(
  31. () => notificationService.success('Updated Product'),
  32. reason => notificationService.error(`Couldnt update product: ${reason as string}`),
  33. );
  34. }
  35. if (loading || !data)
  36. return (
  37. <div className="page-block">
  38. <h3>Loading...</h3>
  39. </div>
  40. );
  41. if (error)
  42. return (
  43. <div className="page-block">
  44. <h3>Error: {error}</h3>
  45. </div>
  46. );
  47. const products = (data as any).products;
  48. return products.items.length ? (
  49. <div className="page-block">
  50. <h3>
  51. Found {products.totalItems} products, showing {products.items.length}:
  52. </h3>
  53. <table className="table">
  54. <thead>
  55. <tr>
  56. <th>Toggle</th>
  57. <th>State</th>
  58. <th>Product</th>
  59. </tr>
  60. </thead>
  61. <tbody>
  62. {products.items.map((p: any, i: any) => (
  63. <tr key={i}>
  64. <td>
  65. <button className="button-ghost" onClick={() => onToggle(p.id, !p.enabled)}>
  66. Toggle
  67. </button>
  68. </td>
  69. <td>
  70. {p.enabled ? (
  71. <span className="label label-success">Enabled</span>
  72. ) : (
  73. <span className="label label-danger">Disabled</span>
  74. )}
  75. </td>
  76. <td>
  77. <Link href={`catalog/inventory/${p.id}`} className="button-ghost">
  78. {p.name}
  79. </Link>
  80. </td>
  81. </tr>
  82. ))}
  83. </tbody>
  84. </table>
  85. </div>
  86. ) : (
  87. <h3>Coudldn't find products.</h3>
  88. );
  89. }