View difference between Paste ID: cdV8caTw and wS9pcCDq
SHOW: | | - or go back to the newest paste.
1-
// pages/cms/products/components/CMSProductForm.tsx
1+
// pages/cms/products/CMSProductsPage.tsx
2-
import clsx from 'clsx';
2+
import { useEffect } from 'react';
3-
import { ChangeEvent, FormEvent, useEffect, useState } from 'react';
3+
import { useProductsService } from '@/services/products';
4-
import { Product } from '@/model/product';
4+
import { ServerError, Spinner } from '@/shared/';
5
import { CMSProductForm } from './components/CMSProductForm';
6-
export interface CMSProductFormProps {
6+
import { CMSProductsList } from './components/CMSProductsList';
7-
  activeItem: Partial<Product> | null;
7+
8-
  onClose: () => void;
8+
export function CMSProductsPage() {
9-
  onAdd: (product: Partial<Product>) => void;
9+
  const { state, actions } = useProductsService();
10-
  onEdit: (product: Partial<Product>) => void;
10+
11
  useEffect(() => {
12
    actions.getProducts()
13-
const initialState: Partial<Product> = {
13+
  }, [])
14-
  name: '', cost: 0, description: ''
14+
15
  return (
16
    <div>
17-
export function CMSProductForm(props: CMSProductFormProps) {
17+
      <h1 className="title">CMS</h1>
18-
  const [formData, setFormData] = useState(initialState);
18+
19
      {state.pending && <Spinner />}
20
      {state.error && <ServerError message={state.error} />}
21-
    if (props.activeItem?.id) {
21+
22-
      setFormData({ ...props.activeItem })
22+
      <CMSProductForm
23-
    } else {
23+
        activeItem={state.activeItem}
24-
      setFormData(initialState)
24+
        onClose={actions.resetActiveItem}
25-
    }
25+
        onAdd={actions.addProduct}
26-
  }, [props.activeItem])
26+
        onEdit={actions.editProduct}
27
      />
28-
  function changeHandler(e: ChangeEvent<HTMLInputElement>) {
28+
29-
    const name = e.currentTarget.value;
29+
      <CMSProductsList
30-
    setFormData(s => ({ ...s, name }))
30+
        items={state.products}
31-
  }
31+
        activeItem={state.activeItem}
32
        onEditItem={actions.setActiveItem}
33-
  function saveHandler(e: FormEvent<HTMLFormElement>) {
33+
        onDeleteItem={actions.deleteProduct}
34-
    e.preventDefault();
34+
      />
35-
    if (props.activeItem?.id) {
35+
36-
      props.onEdit(formData);
36+
      <button
37-
    } else {
37+
        className="btn primary"
38-
      props.onAdd(formData);
38+
        onClick={() => actions.setActiveItem({})}
39-
    }
39+
      >
40-
  }
40+
        ADD NEW
41
      </button>
42-
  const isNameValid = formData.name?.length;
42+
43-
  const isValid = isNameValid;
43+
44
  )
45
}
46-
    <div className={clsx(
46+