Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change products template to use patterns #17

Merged
merged 13 commits into from
May 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions custom-products-catalog/template/.yarnrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
nodeLinker: node-modules
2 changes: 1 addition & 1 deletion custom-products-catalog/template/package.json.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ to: package.json
"name": "<%= packageName %>",
"version": "1.0.0",
"dependencies": {
"@tanstack/react-query": "^4.36.1",
"@wix/dashboard-react": "^1.0.4",
"@wix/sdk-react": "^0.3.8",
"@wix/design-system": "^1.0.0",
"@wix/stores": "^1.0.120",
"@wix/wix-ui-icons-common": "^3.0.34"
"@wix/patterns": "^1.3.0",
},
"devDependencies": {
"@types/react": "^16.0.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,60 +1,55 @@
import React, { useState } from 'react';
import React, { useEffect, useState } from 'react';
import {
Button,
Modal,
CustomModalLayout,
FormField,
Input,
Loader,
} from '@wix/design-system';
import '@wix/design-system/styles.global.css';
import * as Icons from '@wix/wix-ui-icons-common';
import { useCreateProduct } from '../hooks/stores';

export function CreateProduct() {
const createProduct = useCreateProduct();
export function CreateProductModal({ showModal, onSave }: { showModal: boolean, onSave: (name: string) => void }) {
const [productName, setProductName] = useState('');
const [shown, setShown] = useState(false);
const [shown, setShown] = useState(showModal);

useEffect(() => {
setShown(showModal);
}, [showModal])


const toggleModal = () => {
setShown(!shown);
setProductName('');
};

return (
<>
<Button prefixIcon={<Icons.Add />} onClick={toggleModal}>
Add Product
</Button>
<Modal
isOpen={shown}
onRequestClose={toggleModal}
shouldCloseOnOverlayClick
screen="desktop"
>
<CustomModalLayout
title="Create Product"
primaryButtonProps={{
disabled: createProduct.isLoading || !productName,
children: createProduct.isLoading ? <Loader size="tiny" /> : 'Save',
}}
primaryButtonOnClick={async () => {
await createProduct.mutateAsync({ product: { name: productName } });
toggleModal();
}}
secondaryButtonText="Cancel"
secondaryButtonOnClick={toggleModal}
onCloseButtonClick={toggleModal}
content={
<FormField label="Name">
<Input
value={productName}
onChange={(e) => setProductName(e.currentTarget.value)}
/>
</FormField>
}
/>
</Modal>
</>
<Modal
isOpen={shown}
onRequestClose={toggleModal}
shouldCloseOnOverlayClick
screen="desktop"
>
<CustomModalLayout
title="Create Product"
primaryButtonProps={{
disabled: !productName,
children: 'Save',
}}
primaryButtonOnClick={() => {
onSave(productName)
setProductName('')
}}
secondaryButtonText="Cancel"
secondaryButtonOnClick={toggleModal}
onCloseButtonClick={toggleModal}
content={
<FormField label="Name">
<Input
value={productName}
onChange={(e) => setProductName(e.currentTarget.value)}
/>
</FormField>
}
/>
</Modal>
);
}
122 changes: 46 additions & 76 deletions custom-products-catalog/template/src/dashboard/hooks/stores.ts
Original file line number Diff line number Diff line change
@@ -1,89 +1,59 @@
import { products } from '@wix/stores';
import { useWixModules } from '@wix/sdk-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useDashboard } from '@wix/dashboard-react';
import { useCallback } from 'react';
import { CollectionOptimisticActions } from '@wix/patterns';

export function useProductsQuery() {
const { queryProducts } = useWixModules(products);
return useQuery({
queryKey: ['products'],
refetchOnWindowFocus: false,
queryFn: async () => {
const { items } = await queryProducts().descending('lastUpdated').find();
return items;
},
});
}
export function useCreateProduct(optimisticActions: CollectionOptimisticActions<products.Product, {}>) {
const {createProduct} = useWixModules(products);

export function useCreateProduct() {
const queryClient = useQueryClient();
const { showToast } = useDashboard();
const { createProduct } = useWixModules(products);
return useCallback((productName: string) => {
const newProduct: products.Product = {
_id: Date().toString(),
name: productName,
_createdDate: new Date(),
lastUpdated: new Date(),
productType: products.ProductType.physical,
description: 'New Product Description',
priceData: {
currency: 'USD',
price: 10,
},
};
optimisticActions.createOne(newProduct, {
submit: async (products: products.Product[]) => {
const createdProduct = products[0]
const response = await createProduct(createdProduct);
return response.product ? [response.product] : [];
},
successToast: {
message: `${newProduct.name} was successfully created`,
type: 'SUCCESS',
},
errorToast: () => 'Failed to create product',
})
}, [optimisticActions, createProduct]);

return useMutation({
mutationKey: ['createProduct'],
mutationFn: (createProductRequest?: products.CreateProductRequest) => {
return createProduct({
name: 'New Product',
description: 'New Product Description',
priceData: {
currency: 'USD',
price: 10,
},
productType: products.ProductType.physical,
...createProductRequest?.product,
});
},
onError: () =>
showToast({ message: 'Failed to create product', type: 'error' }),
onSuccess: ({ product }) => {
queryClient.setQueryData<products.Product[]>(
['products'],
(oldProducts = []) =>
product ? [product, ...oldProducts] : oldProducts
);
showToast({
message: 'Product created successfully',
type: 'success',
});
},
});
}

export function useDeleteProducts({
productIdsToDelete,
onSuccess,
}: {
productIdsToDelete: Set<string>;
onSuccess?: () => void;
}) {
const queryClient = useQueryClient();
const { showToast } = useDashboard();
export function useDeleteProducts(optimisticActions: CollectionOptimisticActions<products.Product, {}>) {
const { deleteProduct } = useWixModules(products);

return useMutation<products.DeleteProductResponse>({
mutationKey: ['deleteProducts'],
mutationFn: () =>
Promise.all(
[...productIdsToDelete].map((productId) => deleteProduct(productId))
return useCallback((productsToDelete: products.Product[] ) => {
optimisticActions.deleteMany(productsToDelete, {
submit: async (deletedProducts: products.Product[]) => (
await Promise.all(
deletedProducts.map((product) => deleteProduct(product._id!))
)
),
onError: () =>
showToast({ message: 'Failed to delete products', type: 'error' }),
onSuccess: () => {
queryClient.setQueryData<products.Product[]>(
['products'],
(oldProducts = []) =>
oldProducts.filter(
(product: products.Product) => !productIdsToDelete.has(product._id!)
)
);
showToast({
successToast: {
message: `${
productIdsToDelete.size > 1 ? 'Products' : 'Product'
productsToDelete.length > 1 ? 'Products' : 'Product'
} deleted successfully`,
type: 'success',
});
onSuccess?.();
},
});
type: 'SUCCESS',
},
errorToast: () => `Failed to delete ${
productsToDelete.length > 1 ? 'Products' : 'Product'
}`,
});
}, [optimisticActions, deleteProduct]);
}
Loading